forked from loafle/openapi-generator-original
remove custom codegen
This commit is contained in:
parent
f37bd4ab49
commit
d4611e4645
@ -1,74 +0,0 @@
|
|||||||
# Swagger Codegen for the objc-SessionManager library
|
|
||||||
|
|
||||||
## Overview
|
|
||||||
This is a boiler-plate project to generate your own client library with Swagger. It's goal is
|
|
||||||
to get you started with the basic plumbing so you can put in your own logic. It won't work without
|
|
||||||
your changes applied.
|
|
||||||
|
|
||||||
## What's Swagger?
|
|
||||||
The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service.
|
|
||||||
|
|
||||||
|
|
||||||
Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more.
|
|
||||||
|
|
||||||
## How do I use this?
|
|
||||||
At this point, you've likely generated a client setup. It will include something along these lines:
|
|
||||||
|
|
||||||
```
|
|
||||||
.
|
|
||||||
|- README.md // this file
|
|
||||||
|- pom.xml // build script
|
|
||||||
|-- src
|
|
||||||
|--- main
|
|
||||||
|---- java
|
|
||||||
|----- io.swagger.codegen.languages.ObjcSessionmanagerGenerator.java // generator file
|
|
||||||
|---- resources
|
|
||||||
|----- objc-SessionManager // template files
|
|
||||||
|----- META-INF
|
|
||||||
|------ services
|
|
||||||
|------- io.swagger.codegen.CodegenConfig
|
|
||||||
```
|
|
||||||
|
|
||||||
You _will_ need to make changes in at least the following:
|
|
||||||
|
|
||||||
`ObjcSessionmanagerGenerator.java`
|
|
||||||
|
|
||||||
Templates in this folder:
|
|
||||||
|
|
||||||
`src/main/resources/objc-SessionManager`
|
|
||||||
|
|
||||||
Once modified, you can run this:
|
|
||||||
|
|
||||||
```
|
|
||||||
mvn package
|
|
||||||
```
|
|
||||||
|
|
||||||
In your generator project. A single jar file will be produced in `target`. You can now use that with codegen:
|
|
||||||
|
|
||||||
```
|
|
||||||
java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l objc-SessionManager -o ./test
|
|
||||||
```
|
|
||||||
|
|
||||||
Now your templates are available to the client generator and you can write output values
|
|
||||||
|
|
||||||
## But how do I modify this?
|
|
||||||
The `ObjcSessionmanagerGenerator.java` has comments in it--lots of comments. There is no good substitute
|
|
||||||
for reading the code more, though. See how the `ObjcSessionmanagerGenerator` implements `CodegenConfig`.
|
|
||||||
That class has the signature of all values that can be overridden.
|
|
||||||
|
|
||||||
For the templates themselves, you have a number of values available to you for generation.
|
|
||||||
You can execute the `java` command from above while passing different debug flags to show
|
|
||||||
the object you have available during client generation:
|
|
||||||
|
|
||||||
```
|
|
||||||
# The following additional debug options are available for all codegen targets:
|
|
||||||
# -DdebugSwagger prints the OpenAPI Specification as interpreted by the codegen
|
|
||||||
# -DdebugModels prints models passed to the template engine
|
|
||||||
# -DdebugOperations prints operations passed to the template engine
|
|
||||||
# -DdebugSupportingFiles prints additional data passed to the template engine
|
|
||||||
|
|
||||||
java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l objc-SessionManager -o ./test
|
|
||||||
```
|
|
||||||
|
|
||||||
Will, for example, output the debug info for operations. You can use this info
|
|
||||||
in the `api.mustache` file.
|
|
@ -1,102 +0,0 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>io.swagger</groupId>
|
|
||||||
<artifactId>objc-SessionManager-swagger-codegen</artifactId>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
<name>objc-SessionManager-swagger-codegen</name>
|
|
||||||
<version>1.0.0</version>
|
|
||||||
<prerequisites>
|
|
||||||
<maven>2.2.0</maven>
|
|
||||||
</prerequisites>
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>2.12</version>
|
|
||||||
<configuration>
|
|
||||||
<systemProperties>
|
|
||||||
<property>
|
|
||||||
<name>loggerPath</name>
|
|
||||||
<value>conf/log4j.properties</value>
|
|
||||||
</property>
|
|
||||||
</systemProperties>
|
|
||||||
<argLine>-Xms512m -Xmx1500m</argLine>
|
|
||||||
<parallel>methods</parallel>
|
|
||||||
<forkMode>pertest</forkMode>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
|
|
||||||
<!-- attach test jar -->
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-jar-plugin</artifactId>
|
|
||||||
<version>2.2</version>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<goals>
|
|
||||||
<goal>jar</goal>
|
|
||||||
<goal>test-jar</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
<configuration>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.codehaus.mojo</groupId>
|
|
||||||
<artifactId>build-helper-maven-plugin</artifactId>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>add_sources</id>
|
|
||||||
<phase>generate-sources</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>add-source</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<sources>
|
|
||||||
<source>src/main/java</source>
|
|
||||||
</sources>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
<execution>
|
|
||||||
<id>add_test_sources</id>
|
|
||||||
<phase>generate-test-sources</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>add-test-source</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<sources>
|
|
||||||
<source>src/test/java</source>
|
|
||||||
</sources>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<version>2.3.2</version>
|
|
||||||
<configuration>
|
|
||||||
<source>1.6</source>
|
|
||||||
<target>1.6</target>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>io.swagger</groupId>
|
|
||||||
<artifactId>swagger-codegen</artifactId>
|
|
||||||
<version>${swagger-codegen-version}</version>
|
|
||||||
<scope>provided</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
<properties>
|
|
||||||
<swagger-codegen-version>2.2.0-SNAPSHOT</swagger-codegen-version>
|
|
||||||
<maven-plugin-version>1.0.0</maven-plugin-version>
|
|
||||||
<junit-version>4.8.1</junit-version>
|
|
||||||
</properties>
|
|
||||||
</project>
|
|
@ -1,740 +0,0 @@
|
|||||||
package io.swagger.codegen.languages;
|
|
||||||
|
|
||||||
import io.swagger.codegen.*;
|
|
||||||
import io.swagger.models.ArrayModel;
|
|
||||||
import io.swagger.models.Model;
|
|
||||||
import io.swagger.models.properties.*;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
public class ObjcSessionManagerClientCodegen extends DefaultCodegen implements CodegenConfig {
|
|
||||||
public static final String CLASS_PREFIX = "classPrefix";
|
|
||||||
public static final String POD_NAME = "podName";
|
|
||||||
public static final String AUTHOR_NAME = "authorName";
|
|
||||||
public static final String AUTHOR_EMAIL = "authorEmail";
|
|
||||||
public static final String LICENSE = "license";
|
|
||||||
public static final String GIT_REPO_URL = "gitRepoURL";
|
|
||||||
public static final String DEFAULT_LICENSE = "Apache License, Version 2.0";
|
|
||||||
public static final String CORE_DATA = "coreData";
|
|
||||||
|
|
||||||
protected Set<String> foundationClasses = new HashSet<String>();
|
|
||||||
protected String podName = "SwaggerClient";
|
|
||||||
protected String podVersion = "1.0.0";
|
|
||||||
protected String classPrefix = "SWG";
|
|
||||||
protected String authorName = "Swagger";
|
|
||||||
protected String authorEmail = "apiteam@swagger.io";
|
|
||||||
protected String license = DEFAULT_LICENSE;
|
|
||||||
protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen";
|
|
||||||
protected String[] specialWords = {"new", "copy"};
|
|
||||||
protected String apiDocPath = "docs/";
|
|
||||||
protected String modelDocPath = "docs/";
|
|
||||||
protected String modelFilesPath = "Model/";
|
|
||||||
protected String coreFilesPath = "Core/";
|
|
||||||
protected String apiFilesPath = "Api/";
|
|
||||||
|
|
||||||
protected boolean generateCoreData = false;
|
|
||||||
|
|
||||||
protected Set<String> advancedMapingTypes = new HashSet<String>();
|
|
||||||
|
|
||||||
public ObjcSessionManagerClientCodegen() {
|
|
||||||
super();
|
|
||||||
|
|
||||||
outputFolder = "generated-code" + File.separator + "objcSessionManager";
|
|
||||||
modelTemplateFiles.put("model-header.mustache", ".h");
|
|
||||||
modelTemplateFiles.put("model-body.mustache", ".m");
|
|
||||||
apiTemplateFiles.put("api-header.mustache", ".h");
|
|
||||||
apiTemplateFiles.put("api-body.mustache", ".m");
|
|
||||||
embeddedTemplateDir = templateDir = "objcSessionManager";
|
|
||||||
modelDocTemplateFiles.put("model_doc.mustache", ".md");
|
|
||||||
apiDocTemplateFiles.put("api_doc.mustache", ".md");
|
|
||||||
|
|
||||||
defaultIncludes.clear();
|
|
||||||
defaultIncludes.add("bool");
|
|
||||||
defaultIncludes.add("BOOL");
|
|
||||||
defaultIncludes.add("int");
|
|
||||||
defaultIncludes.add("NSURL");
|
|
||||||
defaultIncludes.add("NSString");
|
|
||||||
defaultIncludes.add("NSObject");
|
|
||||||
defaultIncludes.add("NSArray");
|
|
||||||
defaultIncludes.add("NSNumber");
|
|
||||||
defaultIncludes.add("NSDate");
|
|
||||||
defaultIncludes.add("NSDictionary");
|
|
||||||
defaultIncludes.add("NSMutableArray");
|
|
||||||
defaultIncludes.add("NSMutableDictionary");
|
|
||||||
defaultIncludes.add("NSManagedObject");
|
|
||||||
defaultIncludes.add("NSData");
|
|
||||||
|
|
||||||
advancedMapingTypes.add("NSDictionary");
|
|
||||||
advancedMapingTypes.add("NSArray");
|
|
||||||
advancedMapingTypes.add("NSMutableArray");
|
|
||||||
advancedMapingTypes.add("NSMutableDictionary");
|
|
||||||
advancedMapingTypes.add("NSObject");
|
|
||||||
advancedMapingTypes.add("NSNumber");
|
|
||||||
advancedMapingTypes.add("NSURL");
|
|
||||||
advancedMapingTypes.add("NSString");
|
|
||||||
advancedMapingTypes.add("NSDate");
|
|
||||||
|
|
||||||
languageSpecificPrimitives.clear();
|
|
||||||
languageSpecificPrimitives.add("NSNumber");
|
|
||||||
languageSpecificPrimitives.add("NSString");
|
|
||||||
languageSpecificPrimitives.add("NSObject");
|
|
||||||
languageSpecificPrimitives.add("NSDate");
|
|
||||||
languageSpecificPrimitives.add("NSData");
|
|
||||||
languageSpecificPrimitives.add("NSURL");
|
|
||||||
languageSpecificPrimitives.add("bool");
|
|
||||||
languageSpecificPrimitives.add("BOOL");
|
|
||||||
|
|
||||||
typeMapping.clear();
|
|
||||||
typeMapping.put("enum", "NSString");
|
|
||||||
typeMapping.put("date", "NSDate");
|
|
||||||
typeMapping.put("datetime", "NSDate");
|
|
||||||
typeMapping.put("boolean", "NSNumber");
|
|
||||||
typeMapping.put("string", "NSString");
|
|
||||||
typeMapping.put("integer", "NSNumber");
|
|
||||||
typeMapping.put("int", "NSNumber");
|
|
||||||
typeMapping.put("float", "NSNumber");
|
|
||||||
typeMapping.put("long", "NSNumber");
|
|
||||||
typeMapping.put("double", "NSNumber");
|
|
||||||
typeMapping.put("array", "NSArray");
|
|
||||||
typeMapping.put("map", "NSDictionary");
|
|
||||||
typeMapping.put("number", "NSNumber");
|
|
||||||
typeMapping.put("bigdecimal", "NSNumber");
|
|
||||||
typeMapping.put("List", "NSArray");
|
|
||||||
typeMapping.put("object", "NSObject");
|
|
||||||
typeMapping.put("file", "NSURL");
|
|
||||||
typeMapping.put("binary", "NSData");
|
|
||||||
typeMapping.put("bytearray", "NSData");
|
|
||||||
typeMapping.put("byte", "NSData");
|
|
||||||
typeMapping.put("uuid", "NSString");
|
|
||||||
typeMapping.put("password", "NSString");
|
|
||||||
|
|
||||||
// ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm
|
|
||||||
setReservedWordsLowerCase(
|
|
||||||
Arrays.asList(
|
|
||||||
// local variable names in API methods (endpoints)
|
|
||||||
"resourcePath", "pathParams", "queryParams", "headerParams",
|
|
||||||
"responseContentType", "requestContentType", "authSettings",
|
|
||||||
"formParams", "localVarFiles", "bodyParam",
|
|
||||||
// objc reserved words
|
|
||||||
"auto", "else", "long", "switch",
|
|
||||||
"break", "enum", "register", "typedef",
|
|
||||||
"case", "extern", "return", "union",
|
|
||||||
"char", "float", "short", "unsigned",
|
|
||||||
"const", "for", "signed", "void",
|
|
||||||
"continue", "goto", "sizeof", "volatile",
|
|
||||||
"default", "if", "id", "static", "while",
|
|
||||||
"do", "int", "struct", "_Packed",
|
|
||||||
"double", "protocol", "interface", "implementation",
|
|
||||||
"NSObject", "NSInteger", "NSNumber", "CGFloat",
|
|
||||||
"property", "nonatomic", "retain", "strong",
|
|
||||||
"weak", "unsafe_unretained", "readwrite", "readonly",
|
|
||||||
"description"
|
|
||||||
));
|
|
||||||
|
|
||||||
importMapping = new HashMap<String, String>();
|
|
||||||
|
|
||||||
foundationClasses = new HashSet<String>(
|
|
||||||
Arrays.asList(
|
|
||||||
"NSNumber",
|
|
||||||
"NSObject",
|
|
||||||
"NSString",
|
|
||||||
"NSDate",
|
|
||||||
"NSData",
|
|
||||||
"NSURL",
|
|
||||||
"NSDictionary")
|
|
||||||
);
|
|
||||||
|
|
||||||
instantiationTypes.put("array", "NSMutableArray");
|
|
||||||
instantiationTypes.put("map", "NSMutableDictionary");
|
|
||||||
|
|
||||||
cliOptions.clear();
|
|
||||||
cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models").defaultValue("false"));
|
|
||||||
cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`")
|
|
||||||
.defaultValue("SWG"));
|
|
||||||
cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).")
|
|
||||||
.defaultValue("SwaggerClient"));
|
|
||||||
cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version.")
|
|
||||||
.defaultValue("1.0.0"));
|
|
||||||
cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.").defaultValue("Swagger"));
|
|
||||||
cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io"));
|
|
||||||
cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.")
|
|
||||||
.defaultValue("https://github.com/swagger-api/swagger-codegen"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CodegenType getTag() {
|
|
||||||
return CodegenType.CLIENT;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getName() {
|
|
||||||
return "objc-SessionManager";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getHelp() {
|
|
||||||
return "Generates an Objective-C client library.";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void processOpts() {
|
|
||||||
super.processOpts();
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(POD_NAME)) {
|
|
||||||
setPodName((String) additionalProperties.get(POD_NAME));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(CodegenConstants.POD_VERSION)) {
|
|
||||||
setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(CORE_DATA)) {
|
|
||||||
Object coreData = additionalProperties.get(CORE_DATA);
|
|
||||||
if(((String)coreData).equalsIgnoreCase("true")) {
|
|
||||||
generateCoreData = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (additionalProperties.containsKey(CLASS_PREFIX)) {
|
|
||||||
setClassPrefix((String) additionalProperties.get(CLASS_PREFIX));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(AUTHOR_NAME)) {
|
|
||||||
setAuthorName((String) additionalProperties.get(AUTHOR_NAME));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(AUTHOR_EMAIL)) {
|
|
||||||
setAuthorEmail((String) additionalProperties.get(AUTHOR_EMAIL));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(GIT_REPO_URL)) {
|
|
||||||
setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL));
|
|
||||||
}
|
|
||||||
|
|
||||||
if(generateCoreData) {
|
|
||||||
modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h");
|
|
||||||
modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m");
|
|
||||||
modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h");
|
|
||||||
modelTemplateFiles.put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m");
|
|
||||||
}
|
|
||||||
|
|
||||||
additionalProperties.put(POD_NAME, podName);
|
|
||||||
additionalProperties.put(CodegenConstants.POD_VERSION, podVersion);
|
|
||||||
additionalProperties.put(CLASS_PREFIX, classPrefix);
|
|
||||||
additionalProperties.put(AUTHOR_NAME, authorName);
|
|
||||||
additionalProperties.put(AUTHOR_EMAIL, authorEmail);
|
|
||||||
additionalProperties.put(GIT_REPO_URL, gitRepoURL);
|
|
||||||
additionalProperties.put(LICENSE, license);
|
|
||||||
|
|
||||||
// make api and model doc path available in mustache template
|
|
||||||
additionalProperties.put("apiDocPath", apiDocPath);
|
|
||||||
additionalProperties.put("modelDocPath", modelDocPath);
|
|
||||||
additionalProperties.put("useCoreData", generateCoreData);
|
|
||||||
|
|
||||||
modelPackage = podName;
|
|
||||||
apiPackage = podName;
|
|
||||||
|
|
||||||
supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", coreFileFolder(), classPrefix + "Configuration.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec"));
|
|
||||||
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
|
|
||||||
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
|
|
||||||
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
|
|
||||||
|
|
||||||
if(generateCoreData) {
|
|
||||||
supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion"));
|
|
||||||
supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toInstantiationType(Property p) {
|
|
||||||
if (p instanceof MapProperty) {
|
|
||||||
return instantiationTypes.get("map");
|
|
||||||
} else if (p instanceof ArrayProperty) {
|
|
||||||
return instantiationTypes.get("array");
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getTypeDeclaration(String name) {
|
|
||||||
if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) {
|
|
||||||
return name;
|
|
||||||
} else {
|
|
||||||
return name + "*";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getSwaggerType(Property p) {
|
|
||||||
String swaggerType = super.getSwaggerType(p);
|
|
||||||
String type = null;
|
|
||||||
if (typeMapping.containsKey(swaggerType.toLowerCase())) {
|
|
||||||
type = typeMapping.get(swaggerType.toLowerCase());
|
|
||||||
if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) {
|
|
||||||
return toModelNameWithoutReservedWordCheck(type);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
type = swaggerType;
|
|
||||||
}
|
|
||||||
return toModelNameWithoutReservedWordCheck(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getTypeDeclaration(Property p) {
|
|
||||||
if (p instanceof ArrayProperty) {
|
|
||||||
ArrayProperty ap = (ArrayProperty) p;
|
|
||||||
Property inner = ap.getItems();
|
|
||||||
String innerTypeDeclaration = getTypeDeclaration(inner);
|
|
||||||
if (innerTypeDeclaration.endsWith("*")) {
|
|
||||||
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
|
|
||||||
}
|
|
||||||
// In this condition, type of property p is array of primitive,
|
|
||||||
// return container type with pointer, e.g. `NSArray*<NSString*>*'
|
|
||||||
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
|
|
||||||
return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
|
|
||||||
}
|
|
||||||
// In this condition, type of property p is array of model,
|
|
||||||
// return container type combine inner type with pointer, e.g. `NSArray<SWGTag>*'
|
|
||||||
else {
|
|
||||||
for (String sd : advancedMapingTypes) {
|
|
||||||
if(innerTypeDeclaration.startsWith(sd)) {
|
|
||||||
return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
|
|
||||||
}
|
|
||||||
} else if (p instanceof MapProperty) {
|
|
||||||
MapProperty mp = (MapProperty) p;
|
|
||||||
Property inner = mp.getAdditionalProperties();
|
|
||||||
|
|
||||||
String innerTypeDeclaration = getTypeDeclaration(inner);
|
|
||||||
|
|
||||||
if (innerTypeDeclaration.endsWith("*")) {
|
|
||||||
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
|
|
||||||
}
|
|
||||||
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
|
|
||||||
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + "*>*";
|
|
||||||
} else {
|
|
||||||
for (String s : advancedMapingTypes) {
|
|
||||||
if(innerTypeDeclaration.startsWith(s)) {
|
|
||||||
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + "*>*";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + ">*";
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
String swaggerType = getSwaggerType(p);
|
|
||||||
// In this condition, type of p is objective-c primitive type, e.g. `NSSNumber',
|
|
||||||
// return type of p with pointer, e.g. `NSNumber*'
|
|
||||||
if (languageSpecificPrimitives.contains(swaggerType) &&
|
|
||||||
foundationClasses.contains(swaggerType)) {
|
|
||||||
return swaggerType + "*";
|
|
||||||
}
|
|
||||||
// In this condition, type of p is c primitive type, e.g. `bool',
|
|
||||||
// return type of p, e.g. `bool'
|
|
||||||
else if (languageSpecificPrimitives.contains(swaggerType)) {
|
|
||||||
return swaggerType;
|
|
||||||
}
|
|
||||||
// In this condition, type of p is objective-c object type, e.g. `SWGPet',
|
|
||||||
// return type of p with pointer, e.g. `SWGPet*'
|
|
||||||
else {
|
|
||||||
return swaggerType + "*";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isDataTypeBinary(String dataType) {
|
|
||||||
return dataType.toLowerCase().startsWith("nsdata");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toModelName(String type) {
|
|
||||||
// model name cannot use reserved keyword
|
|
||||||
if (reservedWords.contains(type)) {
|
|
||||||
LOGGER.warn(type+ " (reserved word) cannot be used as model name. Renamed to " + ("model_" + type) + " before further processing");
|
|
||||||
type = "model_" + type; // e.g. return => ModelReturn (after camelize)
|
|
||||||
}
|
|
||||||
|
|
||||||
// model name starts with number
|
|
||||||
/* no need for the fix below as objc model starts with prefix (e.g. SWG)
|
|
||||||
if (type.matches("^\\d.*")) {
|
|
||||||
LOGGER.warn(type + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + type));
|
|
||||||
type = "model_" + type; // e.g. 200Response => Model200Response (after camelize)
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
return toModelNameWithoutReservedWordCheck(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Convert input to proper model name according to ObjC style guide
|
|
||||||
* without checking for reserved words
|
|
||||||
*
|
|
||||||
* @param type Model anme
|
|
||||||
* @return model Name in ObjC style guide
|
|
||||||
*/
|
|
||||||
public String toModelNameWithoutReservedWordCheck(String type) {
|
|
||||||
type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
|
|
||||||
|
|
||||||
// language build-in classes
|
|
||||||
if (typeMapping.keySet().contains(type) ||
|
|
||||||
foundationClasses.contains(type) ||
|
|
||||||
importMapping.values().contains(type) ||
|
|
||||||
defaultIncludes.contains(type) ||
|
|
||||||
languageSpecificPrimitives.contains(type)) {
|
|
||||||
return camelize(type);
|
|
||||||
}
|
|
||||||
// custom classes
|
|
||||||
else {
|
|
||||||
if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix
|
|
||||||
type = type + "_" + modelNameSuffix;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!StringUtils.isEmpty(modelNamePrefix)) { // set model prefix
|
|
||||||
type = modelNamePrefix + "_" + type;
|
|
||||||
}
|
|
||||||
|
|
||||||
return classPrefix + camelize(type); // add class prefix
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toModelFilename(String name) {
|
|
||||||
// should be the same as the model name
|
|
||||||
return toModelName(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void setNonArrayMapProperty(CodegenProperty property, String type) {
|
|
||||||
super.setNonArrayMapProperty(property, type);
|
|
||||||
if ("NSDictionary".equals(type)) {
|
|
||||||
property.setter = "initWithDictionary";
|
|
||||||
} else {
|
|
||||||
property.setter = "initWithValues";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toModelImport(String name) {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String apiDocFileFolder() {
|
|
||||||
return (outputFolder + "/" + apiDocPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String modelDocFileFolder() {
|
|
||||||
return (outputFolder + "/" + modelDocPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toModelDocFilename(String name) {
|
|
||||||
return toModelName(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toApiDocFilename(String name) {
|
|
||||||
return toApiName(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String apiFileFolder() {
|
|
||||||
return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String modelFileFolder() {
|
|
||||||
return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String coreFileFolder() {
|
|
||||||
return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toApiName(String name) {
|
|
||||||
return classPrefix + camelize(name) + "Api";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toApiFilename(String name) {
|
|
||||||
return classPrefix + camelize(name) + "Api";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toVarName(String name) {
|
|
||||||
// sanitize name
|
|
||||||
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
|
|
||||||
|
|
||||||
// if it's all upper case, do noting
|
|
||||||
if (name.matches("^[A-Z_]$")) {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
// if name starting with special word, escape with '_'
|
|
||||||
for(int i =0; i < specialWords.length; i++) {
|
|
||||||
if (name.matches("(?i:^" + specialWords[i] + ".*)"))
|
|
||||||
name = escapeSpecialWord(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
// camelize (lower first character) the variable name
|
|
||||||
// e.g. `pet_id` to `petId`
|
|
||||||
name = camelize(name, true);
|
|
||||||
|
|
||||||
// for reserved word or word starting with number, prepend `_`
|
|
||||||
if (isReservedWord(name) || name.matches("^\\d.*")) {
|
|
||||||
name = escapeReservedWord(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toParamName(String name) {
|
|
||||||
// should be the same as variable name
|
|
||||||
return toVarName(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String escapeReservedWord(String name) {
|
|
||||||
return "_" + name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("static-method")
|
|
||||||
public String escapeSpecialWord(String name) {
|
|
||||||
return "var_" + name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toOperationId(String operationId) {
|
|
||||||
// throw exception if method name is empty
|
|
||||||
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)) {
|
|
||||||
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true));
|
|
||||||
operationId = "call_" + operationId;
|
|
||||||
}
|
|
||||||
|
|
||||||
return camelize(sanitizeName(operationId), true);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setClassPrefix(String classPrefix) {
|
|
||||||
this.classPrefix = classPrefix;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPodName(String podName) {
|
|
||||||
this.podName = podName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPodVersion(String podVersion) {
|
|
||||||
this.podVersion = podVersion;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAuthorEmail(String authorEmail) {
|
|
||||||
this.authorEmail = authorEmail;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAuthorName(String authorName) {
|
|
||||||
this.authorName = authorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setGitRepoURL(String gitRepoURL) {
|
|
||||||
this.gitRepoURL = gitRepoURL;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setLicense(String license) {
|
|
||||||
this.license = license;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
|
|
||||||
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
|
|
||||||
if (operations != null) {
|
|
||||||
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
|
|
||||||
for (CodegenOperation operation : ops) {
|
|
||||||
if (!operation.allParams.isEmpty()) {
|
|
||||||
String firstParamName = operation.allParams.get(0).paramName;
|
|
||||||
operation.vendorExtensions.put("firstParamAltName", camelize(firstParamName));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return objs;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void postProcessModelProperty(CodegenModel model, CodegenProperty property){
|
|
||||||
super.postProcessModelProperty(model,property);
|
|
||||||
property.vendorExtensions.put("x-uppercaseName", camelize(property.name));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return the default value of the property
|
|
||||||
*
|
|
||||||
* @param p Swagger property object
|
|
||||||
* @return string presentation of the default value of the property
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public String toDefaultValue(Property p) {
|
|
||||||
if (p instanceof StringProperty) {
|
|
||||||
StringProperty dp = (StringProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@\"" + dp.getDefault().toString() + "\"";
|
|
||||||
}
|
|
||||||
} else if (p instanceof BooleanProperty) {
|
|
||||||
BooleanProperty dp = (BooleanProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
if (dp.getDefault().toString().equalsIgnoreCase("false"))
|
|
||||||
return "@0";
|
|
||||||
else
|
|
||||||
return "@1";
|
|
||||||
}
|
|
||||||
} else if (p instanceof DateProperty) {
|
|
||||||
// TODO
|
|
||||||
} else if (p instanceof DateTimeProperty) {
|
|
||||||
// TODO
|
|
||||||
} else if (p instanceof DoubleProperty) {
|
|
||||||
DoubleProperty dp = (DoubleProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@" + dp.getDefault().toString();
|
|
||||||
}
|
|
||||||
} else if (p instanceof FloatProperty) {
|
|
||||||
FloatProperty dp = (FloatProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@" + dp.getDefault().toString();
|
|
||||||
}
|
|
||||||
} else if (p instanceof IntegerProperty) {
|
|
||||||
IntegerProperty dp = (IntegerProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@" + dp.getDefault().toString();
|
|
||||||
}
|
|
||||||
} else if (p instanceof LongProperty) {
|
|
||||||
LongProperty dp = (LongProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@" + dp.getDefault().toString();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setParameterExampleValue(CodegenParameter p) {
|
|
||||||
String example;
|
|
||||||
|
|
||||||
if (p.defaultValue == null) {
|
|
||||||
example = p.example;
|
|
||||||
} else {
|
|
||||||
example = p.defaultValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
String type = p.baseType;
|
|
||||||
if (type == null) {
|
|
||||||
type = p.dataType;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ("NSString*".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = p.paramName + "_example";
|
|
||||||
}
|
|
||||||
example = "@\"" + escapeText(example) + "\"";
|
|
||||||
} else if ("NSNumber*".equals(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "56";
|
|
||||||
}
|
|
||||||
example = "@" + example;
|
|
||||||
/* OBJC uses NSNumber to represent both int, long, double and float
|
|
||||||
} else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "3.4";
|
|
||||||
} */
|
|
||||||
} else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "True";
|
|
||||||
}
|
|
||||||
} else if ("NSURL*".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "/path/to/file";
|
|
||||||
}
|
|
||||||
//[NSURL fileURLWithPath:@"path/to/file"]
|
|
||||||
example = "[NSURL fileURLWithPath:@\"" + escapeText(example) + "\"]";
|
|
||||||
/*} else if ("NSDate".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "2013-10-20";
|
|
||||||
}
|
|
||||||
example = "'" + escapeText(example) + "'";*/
|
|
||||||
} else if ("NSDate*".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "2013-10-20T19:20:30+01:00";
|
|
||||||
}
|
|
||||||
example = "@\"" + escapeText(example) + "\"";
|
|
||||||
} else if (!languageSpecificPrimitives.contains(type)) {
|
|
||||||
// type is a model class, e.g. User
|
|
||||||
type = type.replace("*", "");
|
|
||||||
// e.g. [[SWGPet alloc] init
|
|
||||||
example = "[[" + type + " alloc] init]";
|
|
||||||
} else {
|
|
||||||
LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (example == null) {
|
|
||||||
example = "NULL";
|
|
||||||
} else if (Boolean.TRUE.equals(p.isListContainer)) {
|
|
||||||
example = "@[" + example + "]";
|
|
||||||
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
|
|
||||||
example = "@{@\"key\" : " + example + "}";
|
|
||||||
}
|
|
||||||
|
|
||||||
p.example = example;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String escapeQuotationMark(String input) {
|
|
||||||
// remove " to avoid code injection
|
|
||||||
return input.replace("\"", "");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String escapeUnsafeCharacters(String input) {
|
|
||||||
return input.replace("*/", "*_/").replace("/*", "/_*");
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
io.swagger.codegen.languages.ObjcSessionManagerClientCodegen
|
|
@ -1,483 +0,0 @@
|
|||||||
#import <ISO8601/NSDate+ISO8601.h>
|
|
||||||
|
|
||||||
#import "{{classPrefix}}ApiSessionManager.h"
|
|
||||||
#import "{{classPrefix}}JSONRequestSerializer.h"
|
|
||||||
#import "{{classPrefix}}JSONResponseSerializer.h"
|
|
||||||
#import "{{classPrefix}}QueryParamCollection.h"
|
|
||||||
#import "{{classPrefix}}DefaultConfiguration.h"
|
|
||||||
|
|
||||||
|
|
||||||
NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject";
|
|
||||||
|
|
||||||
|
|
||||||
static bool offlineState = false;
|
|
||||||
static bool cacheEnabled = false;
|
|
||||||
static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable;
|
|
||||||
static void (^reachabilityChangeBlock)(int);
|
|
||||||
|
|
||||||
|
|
||||||
static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *response) {
|
|
||||||
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
|
|
||||||
return nil;
|
|
||||||
}
|
|
||||||
return ((NSHTTPURLResponse*)response).allHeaderFields;
|
|
||||||
}
|
|
||||||
|
|
||||||
static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) {
|
|
||||||
NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response);
|
|
||||||
if(!headers[@"Content-Disposition"]) {
|
|
||||||
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
|
|
||||||
}
|
|
||||||
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
|
|
||||||
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
|
|
||||||
options:NSRegularExpressionCaseInsensitive
|
|
||||||
error:nil];
|
|
||||||
NSString *contentDispositionHeader = headers[@"Content-Disposition"];
|
|
||||||
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
|
|
||||||
options:0
|
|
||||||
range:NSMakeRange(0, [contentDispositionHeader length])];
|
|
||||||
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@interface {{classPrefix}}ApiSessionManager ()
|
|
||||||
|
|
||||||
@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}ApiSessionManager
|
|
||||||
|
|
||||||
- (instancetype)init {
|
|
||||||
|
|
||||||
return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (instancetype)initWithBaseURL:(NSURL *)url {
|
|
||||||
|
|
||||||
return [self initWithBaseURL:url
|
|
||||||
configuration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]];
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration {
|
|
||||||
|
|
||||||
return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (instancetype)initWithBaseURL:(NSURL *)url
|
|
||||||
configuration:(id<{{classPrefix}}Configuration>)configuration {
|
|
||||||
|
|
||||||
self = [super initWithBaseURL:url];
|
|
||||||
if (self) {
|
|
||||||
_configuration = configuration;
|
|
||||||
_timeoutInterval = 60;
|
|
||||||
_responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init];
|
|
||||||
_sanitizer = [[{{classPrefix}}Sanitizer alloc] init];
|
|
||||||
|
|
||||||
self.requestSerializer = [AFJSONRequestSerializer serializer];
|
|
||||||
self.responseSerializer = [AFJSONResponseSerializer serializer];
|
|
||||||
self.securityPolicy = [self customSecurityPolicy];
|
|
||||||
|
|
||||||
// configure reachability
|
|
||||||
[self configureCacheReachibility];
|
|
||||||
}
|
|
||||||
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Setter Methods
|
|
||||||
|
|
||||||
+ (void) setOfflineState:(BOOL) state {
|
|
||||||
offlineState = state;
|
|
||||||
}
|
|
||||||
|
|
||||||
+ (void) setCacheEnabled:(BOOL)enabled {
|
|
||||||
cacheEnabled = enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status {
|
|
||||||
reachabilityStatus = status;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey {
|
|
||||||
[self.requestSerializer setValue:value forHTTPHeaderField:forKey];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)setRequestSerializer:(AFHTTPRequestSerializer<AFURLRequestSerialization> *)requestSerializer {
|
|
||||||
[super setRequestSerializer:requestSerializer];
|
|
||||||
requestSerializer.timeoutInterval = self.timeoutInterval;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Cache Methods
|
|
||||||
|
|
||||||
+(void)clearCache {
|
|
||||||
[[NSURLCache sharedURLCache] removeAllCachedResponses];
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize
|
|
||||||
diskSize: (unsigned long) diskSize {
|
|
||||||
NSAssert(memorySize > 0, @"invalid in-memory cache size");
|
|
||||||
NSAssert(diskSize >= 0, @"invalid disk cache size");
|
|
||||||
|
|
||||||
NSURLCache *cache =
|
|
||||||
[[NSURLCache alloc]
|
|
||||||
initWithMemoryCapacity:memorySize
|
|
||||||
diskCapacity:diskSize
|
|
||||||
diskPath:@"swagger_url_cache"];
|
|
||||||
|
|
||||||
[NSURLCache setSharedURLCache:cache];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Reachability Methods
|
|
||||||
|
|
||||||
+(AFNetworkReachabilityStatus) getReachabilityStatus {
|
|
||||||
return reachabilityStatus;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(BOOL) getOfflineState {
|
|
||||||
return offlineState;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock {
|
|
||||||
reachabilityChangeBlock = changeBlock;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) configureCacheReachibility {
|
|
||||||
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
|
|
||||||
reachabilityStatus = status;
|
|
||||||
{{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status));
|
|
||||||
[{{classPrefix}}ApiSessionManager setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable];
|
|
||||||
|
|
||||||
// call the reachability block, if configured
|
|
||||||
if (reachabilityChangeBlock != nil) {
|
|
||||||
reachabilityChangeBlock(status);
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
|
|
||||||
[self.reachabilityManager startMonitoring];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Task Methods
|
|
||||||
|
|
||||||
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request
|
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
|
||||||
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
|
|
||||||
{{classPrefix}}DebugLogResponse(response, responseObject,request,error);
|
|
||||||
|
|
||||||
if(!error) {
|
|
||||||
completionBlock(responseObject, nil);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
|
|
||||||
if (responseObject) {
|
|
||||||
// Add in the (parsed) response body.
|
|
||||||
userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject;
|
|
||||||
}
|
|
||||||
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
|
||||||
completionBlock(nil, augmentedError);
|
|
||||||
}];
|
|
||||||
|
|
||||||
return task;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request
|
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
|
||||||
id<{{classPrefix}}Configuration> config = self.configuration;
|
|
||||||
|
|
||||||
NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
|
||||||
{{classPrefix}}DebugLogResponse(response, responseObject,request,error);
|
|
||||||
|
|
||||||
if(error) {
|
|
||||||
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
|
|
||||||
if (responseObject) {
|
|
||||||
userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject;
|
|
||||||
}
|
|
||||||
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
|
||||||
completionBlock(nil, augmentedError);
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory();
|
|
||||||
NSString *filename = {{classPrefix}}__fileNameForResponse(response);
|
|
||||||
|
|
||||||
NSString *filepath = [directory stringByAppendingPathComponent:filename];
|
|
||||||
NSURL *file = [NSURL fileURLWithPath:filepath];
|
|
||||||
|
|
||||||
[responseObject writeToURL:file atomically:YES];
|
|
||||||
|
|
||||||
completionBlock(file, nil);
|
|
||||||
}];
|
|
||||||
|
|
||||||
return task;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Perform Request Methods
|
|
||||||
|
|
||||||
- (NSURLSessionTask*) requestWithPath: (NSString*) path
|
|
||||||
method: (NSString*) method
|
|
||||||
pathParams: (NSDictionary *) pathParams
|
|
||||||
queryParams: (NSDictionary*) queryParams
|
|
||||||
formParams: (NSDictionary *) formParams
|
|
||||||
files: (NSDictionary *) files
|
|
||||||
body: (id) body
|
|
||||||
headerParams: (NSDictionary*) headerParams
|
|
||||||
authSettings: (NSArray *) authSettings
|
|
||||||
requestContentType: (NSString*) requestContentType
|
|
||||||
responseContentType: (NSString*) responseContentType
|
|
||||||
responseType: (NSString *) responseType
|
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
|
||||||
// setting request serializer
|
|
||||||
if ([requestContentType isEqualToString:@"application/json"]) {
|
|
||||||
self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else if ([requestContentType isEqualToString:@"multipart/form-data"]) {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
NSAssert(NO, @"Unsupported request type %@", requestContentType);
|
|
||||||
}
|
|
||||||
|
|
||||||
// setting response serializer
|
|
||||||
if ([responseContentType isEqualToString:@"application/json"]) {
|
|
||||||
self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer];
|
|
||||||
} else {
|
|
||||||
self.responseSerializer = [AFHTTPResponseSerializer serializer];
|
|
||||||
}
|
|
||||||
|
|
||||||
// sanitize parameters
|
|
||||||
pathParams = [self.sanitizer sanitizeForSerialization:pathParams];
|
|
||||||
queryParams = [self.sanitizer sanitizeForSerialization:queryParams];
|
|
||||||
headerParams = [self.sanitizer sanitizeForSerialization:headerParams];
|
|
||||||
formParams = [self.sanitizer sanitizeForSerialization:formParams];
|
|
||||||
if(![body isKindOfClass:[NSData class]]) {
|
|
||||||
body = [self.sanitizer sanitizeForSerialization:body];
|
|
||||||
}
|
|
||||||
|
|
||||||
// auth setting
|
|
||||||
[self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings];
|
|
||||||
|
|
||||||
NSMutableString *resourcePath = [NSMutableString stringWithString:path];
|
|
||||||
[pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
|
||||||
NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj];
|
|
||||||
safeString = {{classPrefix}}PercentEscapedStringFromString(safeString);
|
|
||||||
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
|
|
||||||
}];
|
|
||||||
|
|
||||||
NSMutableURLRequest * request = nil;
|
|
||||||
|
|
||||||
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
|
|
||||||
if ([pathWithQueryParams hasPrefix:@"/"]) {
|
|
||||||
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
|
|
||||||
if (files.count > 0) {
|
|
||||||
__weak __typeof(self)weakSelf = self;
|
|
||||||
request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
|
|
||||||
URLString:urlString
|
|
||||||
parameters:nil
|
|
||||||
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
|
|
||||||
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
|
||||||
NSString *objString = [weakSelf.sanitizer parameterToString:obj];
|
|
||||||
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
|
|
||||||
[formData appendPartWithFormData:data name:key];
|
|
||||||
}];
|
|
||||||
[files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
|
||||||
NSURL *filePath = (NSURL *)obj;
|
|
||||||
[formData appendPartWithFileURL:filePath name:key error:nil];
|
|
||||||
}];
|
|
||||||
} error:nil];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if (formParams) {
|
|
||||||
request = [self.requestSerializer requestWithMethod:method
|
|
||||||
URLString:urlString
|
|
||||||
parameters:formParams
|
|
||||||
error:nil];
|
|
||||||
}
|
|
||||||
if (body) {
|
|
||||||
request = [self.requestSerializer requestWithMethod:method
|
|
||||||
URLString:urlString
|
|
||||||
parameters:body
|
|
||||||
error:nil];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// request cache
|
|
||||||
BOOL hasHeaderParams = [headerParams count] > 0;
|
|
||||||
if (offlineState) {
|
|
||||||
{{classPrefix}}DebugLog(@"%@ cache forced", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
|
|
||||||
}
|
|
||||||
else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) {
|
|
||||||
{{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
{{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasHeaderParams){
|
|
||||||
for(NSString * key in [headerParams keyEnumerator]){
|
|
||||||
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
|
|
||||||
|
|
||||||
[self postProcessRequest:request];
|
|
||||||
|
|
||||||
|
|
||||||
NSURLSessionTask *task = nil;
|
|
||||||
|
|
||||||
if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) {
|
|
||||||
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
|
||||||
completionBlock(data, error);
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
|
||||||
NSError * serializationError;
|
|
||||||
id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError];
|
|
||||||
if(!response && !error){
|
|
||||||
error = serializationError;
|
|
||||||
}
|
|
||||||
completionBlock(response, error);
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
|
|
||||||
[task resume];
|
|
||||||
|
|
||||||
return task;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Added for easier override to modify request
|
|
||||||
- (void)postProcessRequest:(NSMutableURLRequest *)request {
|
|
||||||
// Always disable cookies!
|
|
||||||
[request setHTTPShouldHandleCookies:NO];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark -
|
|
||||||
|
|
||||||
- (NSString*)pathWithQueryParamsToString:(NSString*) path
|
|
||||||
queryParams:(NSDictionary*) queryParams {
|
|
||||||
if(queryParams.count == 0) {
|
|
||||||
return path;
|
|
||||||
}
|
|
||||||
NSString * separator = nil;
|
|
||||||
NSUInteger counter = 0;
|
|
||||||
|
|
||||||
NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path];
|
|
||||||
|
|
||||||
NSDictionary *separatorStyles = @{@"csv" : @",",
|
|
||||||
@"tsv" : @"\t",
|
|
||||||
@"pipes": @"|"
|
|
||||||
};
|
|
||||||
for(NSString * key in [queryParams keyEnumerator]){
|
|
||||||
if (counter == 0) {
|
|
||||||
separator = @"?";
|
|
||||||
} else {
|
|
||||||
separator = @"&";
|
|
||||||
}
|
|
||||||
id queryParam = [queryParams valueForKey:key];
|
|
||||||
if(!queryParam) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
NSString *safeKey = {{classPrefix}}PercentEscapedStringFromString(key);
|
|
||||||
if ([queryParam isKindOfClass:[NSString class]]){
|
|
||||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, {{classPrefix}}PercentEscapedStringFromString(queryParam)]];
|
|
||||||
|
|
||||||
} else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){
|
|
||||||
{{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam;
|
|
||||||
NSArray* values = [coll values];
|
|
||||||
NSString* format = [coll format];
|
|
||||||
|
|
||||||
if([format isEqualToString:@"multi"]) {
|
|
||||||
for(id obj in values) {
|
|
||||||
if (counter > 0) {
|
|
||||||
separator = @"&";
|
|
||||||
}
|
|
||||||
NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]);
|
|
||||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]];
|
|
||||||
counter += 1;
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
NSString * separatorStyle = separatorStyles[format];
|
|
||||||
NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]);
|
|
||||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]];
|
|
||||||
} else {
|
|
||||||
NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]);
|
|
||||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]];
|
|
||||||
}
|
|
||||||
counter += 1;
|
|
||||||
}
|
|
||||||
return requestUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update header and query params based on authentication settings
|
|
||||||
*/
|
|
||||||
- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers
|
|
||||||
queryParams:(NSDictionary *__autoreleasing *)querys
|
|
||||||
WithAuthSettings:(NSArray *)authSettings {
|
|
||||||
|
|
||||||
if (!authSettings || [authSettings count] == 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers];
|
|
||||||
NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys];
|
|
||||||
|
|
||||||
id<{{classPrefix}}Configuration> config = self.configuration;
|
|
||||||
for (NSString *auth in authSettings) {
|
|
||||||
NSDictionary *authSetting = config.authSettings[auth];
|
|
||||||
|
|
||||||
if(!authSetting) { // auth setting is set only if the key is non-empty
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString *type = authSetting[@"in"];
|
|
||||||
NSString *key = authSetting[@"key"];
|
|
||||||
NSString *value = authSetting[@"value"];
|
|
||||||
if ([type isEqualToString:@"header"] && [key length] > 0 ) {
|
|
||||||
headersWithAuth[key] = value;
|
|
||||||
} else if ([type isEqualToString:@"query"] && [key length] != 0) {
|
|
||||||
querysWithAuth[key] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
*headers = [NSDictionary dictionaryWithDictionary:headersWithAuth];
|
|
||||||
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (AFSecurityPolicy *) customSecurityPolicy {
|
|
||||||
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
|
||||||
|
|
||||||
id<{{classPrefix}}Configuration> config = self.configuration;
|
|
||||||
|
|
||||||
if (config.sslCaCert) {
|
|
||||||
NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert];
|
|
||||||
[securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (config.verifySSL) {
|
|
||||||
[securityPolicy setAllowInvalidCertificates:NO];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
[securityPolicy setAllowInvalidCertificates:YES];
|
|
||||||
[securityPolicy setValidatesDomainName:NO];
|
|
||||||
}
|
|
||||||
|
|
||||||
return securityPolicy;
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,149 +0,0 @@
|
|||||||
/**
|
|
||||||
* NOTE: This class is auto generated by the swagger code generator program.
|
|
||||||
* https://github.com/swagger-api/swagger-codegen
|
|
||||||
* Do not edit the class manually.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#import <AFNetworking/AFNetworking.h>
|
|
||||||
#import "{{classPrefix}}Configuration.h"
|
|
||||||
#import "{{classPrefix}}ResponseDeserializer.h"
|
|
||||||
#import "{{classPrefix}}Sanitizer.h"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A key for `NSError` user info dictionaries.
|
|
||||||
*
|
|
||||||
* The corresponding value is the parsed response body for an HTTP error.
|
|
||||||
*/
|
|
||||||
extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
|
|
||||||
|
|
||||||
|
|
||||||
@interface {{classPrefix}}ApiSessionManager : AFHTTPSessionManager
|
|
||||||
|
|
||||||
@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration;
|
|
||||||
|
|
||||||
@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
|
|
||||||
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
|
|
||||||
@property(nonatomic, readonly) NSOperationQueue* queue;
|
|
||||||
|
|
||||||
@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer;
|
|
||||||
|
|
||||||
@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clears Cache
|
|
||||||
*/
|
|
||||||
+(void)clearCache;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Turns on cache
|
|
||||||
*
|
|
||||||
* @param enabled If the cached is enable, must be `YES` or `NO`
|
|
||||||
*/
|
|
||||||
+(void)setCacheEnabled:(BOOL) enabled;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the client unreachable
|
|
||||||
*
|
|
||||||
* @param state off line state, must be `YES` or `NO`
|
|
||||||
*/
|
|
||||||
+(void) setOfflineState:(BOOL) state;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets if the client is unreachable
|
|
||||||
*
|
|
||||||
* @return The client offline state
|
|
||||||
*/
|
|
||||||
+(BOOL) getOfflineState;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the client reachability, this may be overridden by the reachability manager if reachability changes
|
|
||||||
*
|
|
||||||
* @param The client reachability.
|
|
||||||
*/
|
|
||||||
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the client reachability
|
|
||||||
*
|
|
||||||
* @return The client reachability.
|
|
||||||
*/
|
|
||||||
+(AFNetworkReachabilityStatus) getReachabilityStatus;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Customizes the behavior when the reachability changed
|
|
||||||
*
|
|
||||||
* @param changeBlock The block will be executed when the reachability changed.
|
|
||||||
*/
|
|
||||||
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the api client reachability strategy
|
|
||||||
*/
|
|
||||||
- (void)configureCacheReachibility;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets header for request
|
|
||||||
*
|
|
||||||
* @param value The header value
|
|
||||||
* @param forKey The header key
|
|
||||||
*/
|
|
||||||
-(void)setHeaderValue:(NSString*) value
|
|
||||||
forKey:(NSString*) forKey;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates header parameters and query parameters for authentication
|
|
||||||
*
|
|
||||||
* @param headers The header parameter will be udpated, passed by pointer to pointer.
|
|
||||||
* @param querys The query parameters will be updated, passed by pointer to pointer.
|
|
||||||
* @param authSettings The authentication names NSArray.
|
|
||||||
*/
|
|
||||||
- (void) updateHeaderParams:(NSDictionary **)headers
|
|
||||||
queryParams:(NSDictionary **)querys
|
|
||||||
WithAuthSettings:(NSArray *)authSettings;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes the session manager with a configuration.
|
|
||||||
*
|
|
||||||
* @param configuration The configuration implementation
|
|
||||||
*/
|
|
||||||
- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Performs request
|
|
||||||
*
|
|
||||||
* @param path Request url.
|
|
||||||
* @param method Request method.
|
|
||||||
* @param pathParams Request path parameters.
|
|
||||||
* @param queryParams Request query parameters.
|
|
||||||
* @param body Request body.
|
|
||||||
* @param headerParams Request header parameters.
|
|
||||||
* @param authSettings Request authentication names.
|
|
||||||
* @param requestContentType Request content-type.
|
|
||||||
* @param responseContentType Response content-type.
|
|
||||||
* @param completionBlock The block will be executed when the request completed.
|
|
||||||
*
|
|
||||||
* @return The created session task.
|
|
||||||
*/
|
|
||||||
- (NSURLSessionTask*) requestWithPath: (NSString*) path
|
|
||||||
method: (NSString*) method
|
|
||||||
pathParams: (NSDictionary *) pathParams
|
|
||||||
queryParams: (NSDictionary*) queryParams
|
|
||||||
formParams: (NSDictionary *) formParams
|
|
||||||
files: (NSDictionary *) files
|
|
||||||
body: (id) body
|
|
||||||
headerParams: (NSDictionary*) headerParams
|
|
||||||
authSettings: (NSArray *) authSettings
|
|
||||||
requestContentType: (NSString*) requestContentType
|
|
||||||
responseContentType: (NSString*) responseContentType
|
|
||||||
responseType: (NSString *) responseType
|
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Custom security policy
|
|
||||||
*
|
|
||||||
* @return AFSecurityPolicy
|
|
||||||
*/
|
|
||||||
- (AFSecurityPolicy *) customSecurityPolicy;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,19 +0,0 @@
|
|||||||
#import "{{classPrefix}}BasicAuthTokenProvider.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}BasicAuthTokenProvider
|
|
||||||
|
|
||||||
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password {
|
|
||||||
|
|
||||||
// return empty string if username and password are empty
|
|
||||||
if (username.length == 0 && password.length == 0){
|
|
||||||
return @"";
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
|
|
||||||
NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding];
|
|
||||||
basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]];
|
|
||||||
|
|
||||||
return basicAuthCredentials;
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,14 +0,0 @@
|
|||||||
/** The `{{classPrefix}}BasicAuthTokenProvider` class creates a basic auth token from username and password.
|
|
||||||
*
|
|
||||||
* NOTE: This class is auto generated by the swagger code generator program.
|
|
||||||
* https://github.com/swagger-api/swagger-codegen
|
|
||||||
* Do not edit the class manually.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#import <Foundation/Foundation.h>
|
|
||||||
|
|
||||||
@interface {{classPrefix}}BasicAuthTokenProvider : NSObject
|
|
||||||
|
|
||||||
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,75 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import "{{classPrefix}}Logger.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@protocol {{classPrefix}}Configuration <NSObject>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api logger
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) {{classPrefix}}Logger *logger;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Base url
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *host;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api key values for Api Key type Authentication
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSDictionary *apiKey;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api key prefix values to be prepend to the respective api key
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSDictionary *apiKeyPrefix;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Username for HTTP Basic Authentication
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *username;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Password for HTTP Basic Authentication
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *password;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Access token for OAuth
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *accessToken;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Temp folder for file download
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *tempFolderPath;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Debug switch, default false
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) BOOL debug;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SSL/TLS verification
|
|
||||||
* Set this to NO to skip verifying SSL certificate when calling API from https server
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) BOOL verifySSL;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SSL/TLS verification
|
|
||||||
* Set this to customize the certificate file to verify the peer
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *sslCaCert;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Authentication Settings
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSDictionary *authSettings;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default headers for all services
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,159 +0,0 @@
|
|||||||
#import "{{classPrefix}}DefaultConfiguration.h"
|
|
||||||
#import "{{classPrefix}}BasicAuthTokenProvider.h"
|
|
||||||
|
|
||||||
@interface {{classPrefix}}DefaultConfiguration ()
|
|
||||||
|
|
||||||
@property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders;
|
|
||||||
@property (nonatomic, strong) NSMutableDictionary *mutableApiKey;
|
|
||||||
@property (nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}DefaultConfiguration
|
|
||||||
|
|
||||||
#pragma mark - Singleton Methods
|
|
||||||
|
|
||||||
+ (instancetype)sharedConfiguration {
|
|
||||||
|
|
||||||
static {{classPrefix}}DefaultConfiguration *shardConfig = nil;
|
|
||||||
static dispatch_once_t onceToken;
|
|
||||||
dispatch_once(&onceToken, ^{
|
|
||||||
shardConfig = [[self alloc] init];
|
|
||||||
});
|
|
||||||
return shardConfig;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Initialize Methods
|
|
||||||
|
|
||||||
- (instancetype)init {
|
|
||||||
self = [super init];
|
|
||||||
if (self) {
|
|
||||||
_host = @"{{basePath}}";
|
|
||||||
_username = @"";
|
|
||||||
_password = @"";
|
|
||||||
_accessToken= @"";
|
|
||||||
_verifySSL = YES;
|
|
||||||
_mutableApiKey = [NSMutableDictionary dictionary];
|
|
||||||
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
|
|
||||||
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
|
|
||||||
{{#httpUserAgent}}_mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}"{{/httpUserAgent}};
|
|
||||||
_logger = [{{classPrefix}}Logger sharedLogger];
|
|
||||||
}
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Instance Methods
|
|
||||||
|
|
||||||
- (NSString *) getApiKeyWithPrefix:(NSString *)key {
|
|
||||||
NSString *prefix = self.apiKeyPrefix[key];
|
|
||||||
NSString *apiKey = self.apiKey[key];
|
|
||||||
if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set
|
|
||||||
return [NSString stringWithFormat:@"%@ %@", prefix, apiKey];
|
|
||||||
}
|
|
||||||
else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix
|
|
||||||
return [NSString stringWithFormat:@"%@", self.apiKey[key]];
|
|
||||||
}
|
|
||||||
else { // return empty string if nothing is set
|
|
||||||
return @"";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSString *) getBasicAuthToken {
|
|
||||||
|
|
||||||
NSString *basicAuthToken = [{{classPrefix}}BasicAuthTokenProvider createBasicAuthTokenWithUsername:self.username password:self.password];
|
|
||||||
return basicAuthToken;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSString *) getAccessToken {
|
|
||||||
if (self.accessToken.length == 0) { // token not set, return empty string
|
|
||||||
return @"";
|
|
||||||
} else {
|
|
||||||
return [NSString stringWithFormat:@"Bearer %@", self.accessToken];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Setter Methods
|
|
||||||
|
|
||||||
- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier {
|
|
||||||
[self.mutableApiKey setValue:apiKey forKey:identifier];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) removeApiKey:(NSString *)identifier {
|
|
||||||
[self.mutableApiKey removeObjectForKey:identifier];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier {
|
|
||||||
[self.mutableApiKeyPrefix setValue:prefix forKey:identifier];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) removeApiKeyPrefix:(NSString *)identifier {
|
|
||||||
[self.mutableApiKeyPrefix removeObjectForKey:identifier];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark -
|
|
||||||
|
|
||||||
- (NSDictionary *) authSettings {
|
|
||||||
return @{
|
|
||||||
{{#authMethods}}
|
|
||||||
{{#isApiKey}}
|
|
||||||
@"{{name}}":
|
|
||||||
@{
|
|
||||||
@"type": @"api_key",
|
|
||||||
@"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}},
|
|
||||||
@"key": @"{{keyParamName}}",
|
|
||||||
@"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"]
|
|
||||||
},
|
|
||||||
{{/isApiKey}}
|
|
||||||
{{#isBasic}}
|
|
||||||
@"{{name}}":
|
|
||||||
@{
|
|
||||||
@"type": @"basic",
|
|
||||||
@"in": @"header",
|
|
||||||
@"key": @"Authorization",
|
|
||||||
@"value": [self getBasicAuthToken]
|
|
||||||
},
|
|
||||||
{{/isBasic}}
|
|
||||||
{{#isOAuth}}
|
|
||||||
@"{{name}}":
|
|
||||||
@{
|
|
||||||
@"type": @"oauth",
|
|
||||||
@"in": @"header",
|
|
||||||
@"key": @"Authorization",
|
|
||||||
@"value": [self getAccessToken]
|
|
||||||
},
|
|
||||||
{{/isOAuth}}
|
|
||||||
{{/authMethods}}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
-(BOOL)debug {
|
|
||||||
return self.logger.isEnabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void)setDebug:(BOOL)debug {
|
|
||||||
self.logger.enabled = debug;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
|
|
||||||
if(!value) {
|
|
||||||
[self.mutableDefaultHeaders removeObjectForKey:key];
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.mutableDefaultHeaders[key] = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void) removeDefaultHeaderForKey:(NSString*)key {
|
|
||||||
[self.mutableDefaultHeaders removeObjectForKey:key];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSString *)defaultHeaderForKey:(NSString *)key {
|
|
||||||
return self.mutableDefaultHeaders[key];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSDictionary *)defaultHeaders {
|
|
||||||
return [self.mutableDefaultHeaders copy];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,129 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import "{{classPrefix}}Configuration.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration>
|
|
||||||
|
|
||||||
+ ({{classPrefix}}DefaultConfiguration *)sharedConfiguration;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default api logger
|
|
||||||
*/
|
|
||||||
@property (nonatomic, strong) {{classPrefix}}Logger * logger;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default base url
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *host;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api key values for Api Key type Authentication
|
|
||||||
*
|
|
||||||
* To add or remove api key, use `setApiKey:forApiKeyIdentifier:`.
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic, strong) NSDictionary *apiKey;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api key prefix values to be prepend to the respective api key
|
|
||||||
*
|
|
||||||
* To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`.
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Username for HTTP Basic Authentication
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *username;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Password for HTTP Basic Authentication
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *password;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Access token for OAuth
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *accessToken;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Temp folder for file download
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *tempFolderPath;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Debug switch, default false
|
|
||||||
*/
|
|
||||||
@property (nonatomic) BOOL debug;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SSL/TLS verification
|
|
||||||
* Set this to NO to skip verifying SSL certificate when calling API from https server
|
|
||||||
*/
|
|
||||||
@property (nonatomic) BOOL verifySSL;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SSL/TLS verification
|
|
||||||
* Set this to customize the certificate file to verify the peer
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *sslCaCert;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets API key
|
|
||||||
*
|
|
||||||
* To remove a apiKey for an identifier, just set the apiKey to nil.
|
|
||||||
*
|
|
||||||
* @param apiKey API key or token.
|
|
||||||
* @param identifier API key identifier (authentication schema).
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes api key
|
|
||||||
*
|
|
||||||
* @param identifier API key identifier.
|
|
||||||
*/
|
|
||||||
- (void) removeApiKey:(NSString *)identifier;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the prefix for API key
|
|
||||||
*
|
|
||||||
* @param apiKeyPrefix API key prefix.
|
|
||||||
* @param identifier API key identifier.
|
|
||||||
*/
|
|
||||||
- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes api key prefix
|
|
||||||
*
|
|
||||||
* @param identifier API key identifier.
|
|
||||||
*/
|
|
||||||
- (void) removeApiKeyPrefix:(NSString *)identifier;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default headers for all services
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes header from defaultHeaders
|
|
||||||
*
|
|
||||||
* @param Header name.
|
|
||||||
*/
|
|
||||||
-(void) removeDefaultHeaderForKey:(NSString*)key;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the header for key
|
|
||||||
*
|
|
||||||
* @param value Value for header name
|
|
||||||
* @param key Header name
|
|
||||||
*/
|
|
||||||
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param Header key name.
|
|
||||||
*/
|
|
||||||
-(NSString*) defaultHeaderForKey:(NSString*)key;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,37 +0,0 @@
|
|||||||
#import "{{classPrefix}}JSONRequestSerializer.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}JSONRequestSerializer
|
|
||||||
|
|
||||||
///
|
|
||||||
/// When customize a request serializer,
|
|
||||||
/// the serializer must conform the protocol `AFURLRequestSerialization`
|
|
||||||
/// and implements the protocol method `requestBySerializingRequest:withParameters:error:`
|
|
||||||
///
|
|
||||||
/// @param request The original request.
|
|
||||||
/// @param parameters The parameters to be encoded.
|
|
||||||
/// @param error The error that occurred while attempting to encode the request parameters.
|
|
||||||
///
|
|
||||||
/// @return A serialized request.
|
|
||||||
///
|
|
||||||
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
|
|
||||||
withParameters:(id)parameters
|
|
||||||
error:(NSError *__autoreleasing *)error
|
|
||||||
{
|
|
||||||
if (!parameters) {
|
|
||||||
return request;
|
|
||||||
}
|
|
||||||
// If the body data which will be serialized isn't NSArray or NSDictionary
|
|
||||||
// then put the data in the http request body directly.
|
|
||||||
if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) {
|
|
||||||
return [super requestBySerializingRequest:request withParameters:parameters error:error];
|
|
||||||
}
|
|
||||||
NSMutableURLRequest *mutableRequest = [request mutableCopy];
|
|
||||||
if([parameters isKindOfClass:[NSData class]]) {
|
|
||||||
[mutableRequest setHTTPBody:parameters];
|
|
||||||
} else {
|
|
||||||
[mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]];
|
|
||||||
}
|
|
||||||
return mutableRequest;
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,7 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <AFNetworking/AFURLRequestSerialization.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}JSONRequestSerializer : AFJSONRequestSerializer
|
|
||||||
@end
|
|
@ -1,39 +0,0 @@
|
|||||||
#import "{{classPrefix}}JSONResponseSerializer.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}JSONResponseSerializer
|
|
||||||
|
|
||||||
///
|
|
||||||
/// When customize a response serializer,
|
|
||||||
/// the serializer must conform the protocol `AFURLResponseSerialization`
|
|
||||||
/// and implements the protocol method `responseObjectForResponse:error:`
|
|
||||||
///
|
|
||||||
/// @param response The response to be processed.
|
|
||||||
/// @param data The response data to be decoded.
|
|
||||||
/// @param error The error that occurred while attempting to decode the response data.
|
|
||||||
///
|
|
||||||
/// @return The object decoded from the specified response data.
|
|
||||||
///
|
|
||||||
- (id) responseObjectForResponse:(NSURLResponse *)response
|
|
||||||
data:(NSData *)data
|
|
||||||
error:(NSError *__autoreleasing *)error {
|
|
||||||
NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error];
|
|
||||||
|
|
||||||
// if response data is not a valid json, return string of data.
|
|
||||||
if ([self isParseError:*error]) {
|
|
||||||
*error = nil;
|
|
||||||
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
|
||||||
return responseString;
|
|
||||||
}
|
|
||||||
|
|
||||||
return responseJson;
|
|
||||||
}
|
|
||||||
|
|
||||||
-(BOOL)isParseError:(NSError *)error {
|
|
||||||
return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840;
|
|
||||||
}
|
|
||||||
|
|
||||||
+ (instancetype)serializer {
|
|
||||||
return [self serializerWithReadingOptions:NSJSONReadingAllowFragments];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,8 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <AFNetworking/AFURLResponseSerialization.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer
|
|
||||||
|
|
||||||
@end
|
|
@ -1,11 +0,0 @@
|
|||||||
#import <ISO8601/NSDate+ISO8601.h>
|
|
||||||
#import "JSONValueTransformer+ISO8601.h"
|
|
||||||
|
|
||||||
@implementation JSONValueTransformer (ISO8601)
|
|
||||||
|
|
||||||
- (NSDate *) NSDateFromNSString:(NSString *)string
|
|
||||||
{
|
|
||||||
return [NSDate dateWithISO8601String:string];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,8 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <JSONModel/JSONValueTransformer.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface JSONValueTransformer (ISO8601)
|
|
||||||
|
|
||||||
@end
|
|
@ -1,74 +0,0 @@
|
|||||||
#import "{{classPrefix}}Logger.h"
|
|
||||||
|
|
||||||
@interface {{classPrefix}}Logger ()
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}Logger
|
|
||||||
|
|
||||||
+ (instancetype) sharedLogger {
|
|
||||||
static {{classPrefix}}Logger *shardLogger = nil;
|
|
||||||
static dispatch_once_t onceToken;
|
|
||||||
dispatch_once(&onceToken, ^{
|
|
||||||
shardLogger = [[self alloc] init];
|
|
||||||
});
|
|
||||||
return shardLogger;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Log Methods
|
|
||||||
|
|
||||||
- (void)debugLog:(NSString *)method
|
|
||||||
message:(NSString *)format, ... {
|
|
||||||
if (!self.isEnabled) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSMutableString *message = [NSMutableString stringWithCapacity:1];
|
|
||||||
|
|
||||||
if (method) {
|
|
||||||
[message appendFormat:@"%@: ", method];
|
|
||||||
}
|
|
||||||
|
|
||||||
va_list args;
|
|
||||||
va_start(args, format);
|
|
||||||
|
|
||||||
[message appendString:[[NSString alloc] initWithFormat:format arguments:args]];
|
|
||||||
|
|
||||||
// If set logging file handler, log into file,
|
|
||||||
// otherwise log into console.
|
|
||||||
if (self.loggingFileHandler) {
|
|
||||||
[self.loggingFileHandler seekToEndOfFile];
|
|
||||||
[self.loggingFileHandler writeData:[message dataUsingEncoding:NSUTF8StringEncoding]];
|
|
||||||
} else {
|
|
||||||
NSLog(@"%@", message);
|
|
||||||
}
|
|
||||||
|
|
||||||
va_end(args);
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error {
|
|
||||||
NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\
|
|
||||||
"[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n",
|
|
||||||
[[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding],
|
|
||||||
responseObject];
|
|
||||||
|
|
||||||
{{classPrefix}}DebugLog(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) setLoggingFile:(NSString *)loggingFile {
|
|
||||||
if(_loggingFile == loggingFile) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// close old file handler
|
|
||||||
if ([self.loggingFileHandler isKindOfClass:[NSFileHandle class]]) {
|
|
||||||
[self.loggingFileHandler closeFile];
|
|
||||||
}
|
|
||||||
_loggingFile = loggingFile;
|
|
||||||
_loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile];
|
|
||||||
if (_loggingFileHandler == nil) {
|
|
||||||
[[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil];
|
|
||||||
_loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,50 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
#ifndef {{classPrefix}}DebugLogResponse
|
|
||||||
#define {{classPrefix}}DebugLogResponse(response, responseObject,request, error) [[{{classPrefix}}Logger sharedLogger] logResponse:response responseObject:responseObject request:request error:error];
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Log debug message macro
|
|
||||||
*/
|
|
||||||
#ifndef {{classPrefix}}DebugLog
|
|
||||||
#define {{classPrefix}}DebugLog(format, ...) [[{{classPrefix}}Logger sharedLogger] debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__];
|
|
||||||
#endif
|
|
||||||
|
|
||||||
@interface {{classPrefix}}Logger : NSObject
|
|
||||||
|
|
||||||
+(instancetype)sharedLogger;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Enabled switch, default NO - default set by {{classPrefix}}Configuration debug property
|
|
||||||
*/
|
|
||||||
@property (nonatomic, assign, getter=isEnabled) BOOL enabled;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Debug file location, default log in console
|
|
||||||
*/
|
|
||||||
@property (nonatomic, strong) NSString *loggingFile;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Log file handler, this property is used by sdk internally.
|
|
||||||
*/
|
|
||||||
@property (nonatomic, strong, readonly) NSFileHandle *loggingFileHandler;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Log debug message
|
|
||||||
*/
|
|
||||||
-(void)debugLog:(NSString *)method message:(NSString *)format, ...;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Logs request and response
|
|
||||||
*
|
|
||||||
* @param response NSURLResponse for the HTTP request.
|
|
||||||
* @param responseObject response object of the HTTP request.
|
|
||||||
* @param request The HTTP request.
|
|
||||||
* @param error The error of the HTTP request.
|
|
||||||
*/
|
|
||||||
- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,12 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
||||||
<model userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="9525" systemVersion="15D21" minimumToolsVersion="Xcode 7.0">
|
|
||||||
|
|
||||||
{{#models}}{{#model}}<entity name="{{{classname}}}ManagedObject" representedClassName="{{{classname}}}ManagedObject" syncable="YES">
|
|
||||||
{{#isArrayModel}} <relationship name="entries" optional="YES" toMany="YES" deletionRule="Cascade" destinationEntity="{{{arrayModelType}}}ManagedObject" syncable="YES"/>
|
|
||||||
{{/isArrayModel}}{{^isArrayModel}}{{#vars}}{{#complexType}} <relationship name="{{name}}" {{^required}}optional="YES"{{/required}} {{#isListContainer}}toMany="YES"{{/isListContainer}}{{^isListContainer}}maxCount="1"{{/isListContainer}} deletionRule="Cascade" destinationEntity="{{{complexType}}}ManagedObject" syncable="YES"/>{{/complexType}}{{^complexType}} <attribute name="{{name}}" {{^required}}optional="YES"{{/required}} attributeType="{{#isString}}String{{/isString}}{{#isInteger}}Integer 16{{/isInteger}}{{#isLong}}Double{{/isLong}}{{#isDouble}}Double{{/isDouble}}{{#isFloat}}Float{{/isFloat}}{{#isByteArray}}Binary{{/isByteArray}}{{#isBinary}}Binary{{/isBinary}}{{#isListContainer}}Transformable{{/isListContainer}}{{#isMapContainer}}Transformable{{/isMapContainer}}{{#isBoolean}}Boolean{{/isBoolean}}{{#isDate}}Date{{/isDate}}{{#isDateTime}}Date{{/isDateTime}}" syncable="YES"/>{{/complexType}}{{#vendorExtensions.x-is-unique}}
|
|
||||||
<uniquenessConstraints><uniquenessConstraint><constraint value="{{name}}"/></uniquenessConstraint></uniquenessConstraints>{{/vendorExtensions.x-is-unique}}
|
|
||||||
{{/vars}}
|
|
||||||
{{/isArrayModel}}
|
|
||||||
</entity>
|
|
||||||
{{/model}}{{/models}}
|
|
||||||
</model>
|
|
@ -1,20 +0,0 @@
|
|||||||
{{#models}}
|
|
||||||
{{#model}}
|
|
||||||
#import "{{classname}}ManagedObject.h"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* NOTE: This class is auto generated by the swagger code generator program.
|
|
||||||
* https://github.com/swagger-api/swagger-codegen
|
|
||||||
* Do not edit the class manually.
|
|
||||||
*/
|
|
||||||
@implementation {{classname}}ManagedObject
|
|
||||||
{{#isArrayModel}}
|
|
||||||
|
|
||||||
@dynamic entries;
|
|
||||||
|
|
||||||
{{/isArrayModel}}{{^isArrayModel}}{{#vars}}
|
|
||||||
@dynamic {{name}};{{/vars}}
|
|
||||||
{{/isArrayModel}}
|
|
||||||
{{/model}}
|
|
||||||
@end
|
|
||||||
{{/models}}
|
|
@ -1,49 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <CoreData/CoreData.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
{{#imports}}#import "{{import}}ManagedObject.h"
|
|
||||||
{{/imports}}
|
|
||||||
{{newline}}
|
|
||||||
{{#models}}
|
|
||||||
{{#model}}
|
|
||||||
|
|
||||||
NS_ASSUME_NONNULL_BEGIN
|
|
||||||
{{#isArrayModel}}
|
|
||||||
|
|
||||||
@interface {{classname}}ManagedObject : NSManagedObject
|
|
||||||
|
|
||||||
@property (nullable, nonatomic, retain) NSSet<{{{arrayModelType}}}ManagedObject*>* entries;
|
|
||||||
|
|
||||||
{{/isArrayModel}}{{^isArrayModel}}
|
|
||||||
@interface {{classname}}ManagedObject : {{#parent}}{{{parent}}}ManagedObject{{/parent}}{{^parent}}NSManagedObject{{/parent}}
|
|
||||||
|
|
||||||
{{#vars}}
|
|
||||||
{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}}
|
|
||||||
*/{{/description}}
|
|
||||||
@property (nullable, nonatomic, retain) {{^complexType}}{{{ datatype }}}{{/complexType}}{{#complexType}}{{#isListContainer}}NSSet<{{{complexType}}}ManagedObject*>*{{/isListContainer}}{{^isListContainer}}{{#isMapContainer}}{{{ datatype }}}{{/isMapContainer}}{{^isMapContainer}}{{{complexType}}}ManagedObject*{{/isMapContainer}}{{/isListContainer}}{{/complexType}} {{name}};
|
|
||||||
{{/vars}}
|
|
||||||
{{/isArrayModel}}
|
|
||||||
@end
|
|
||||||
|
|
||||||
@interface {{classname}}ManagedObject (GeneratedAccessors)
|
|
||||||
{{#isArrayModel}}
|
|
||||||
- (void)addEntriesObject:({{arrayModelType}}ManagedObject *)value;
|
|
||||||
- (void)removeEntriesObject:({{arrayModelType}}ManagedObject *)value;
|
|
||||||
- (void)addEntries:(NSSet<{{{arrayModelType}}}ManagedObject*> *)values;
|
|
||||||
- (void)removeEntries:(NSSet<{{{arrayModelType}}}ManagedObject*> *)values;
|
|
||||||
{{/isArrayModel}}
|
|
||||||
{{^isArrayModel}}
|
|
||||||
{{#vars}}{{#isListContainer}}{{#complexType}}- (void)add{{vendorExtensions.x-uppercaseName}}Object:({{complexType}}ManagedObject *)value;
|
|
||||||
- (void)remove{{vendorExtensions.x-uppercaseName}}Object:({{complexType}}ManagedObject *)value;
|
|
||||||
- (void)add{{vendorExtensions.x-uppercaseName}}:(NSSet<{{{complexType}}}ManagedObject*> *)values;
|
|
||||||
- (void)remove{{vendorExtensions.x-uppercaseName}}:(NSSet<{{{complexType}}}ManagedObject*> *)values;
|
|
||||||
{{/complexType}}{{/isListContainer}}{{/vars}}
|
|
||||||
{{/isArrayModel}}
|
|
||||||
@end
|
|
||||||
|
|
||||||
|
|
||||||
NS_ASSUME_NONNULL_END
|
|
||||||
{{/model}}
|
|
||||||
{{/models}}
|
|
@ -1,89 +0,0 @@
|
|||||||
|
|
||||||
{{#models}}{{#model}}
|
|
||||||
#import "{{classname}}ManagedObjectBuilder.h"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* NOTE: This class is auto generated by the swagger code generator program.
|
|
||||||
* https://github.com/swagger-api/swagger-codegen
|
|
||||||
* Do not edit the class manually.
|
|
||||||
*/
|
|
||||||
|
|
||||||
@implementation {{classname}}ManagedObjectBuilder
|
|
||||||
|
|
||||||
-(instancetype)init {
|
|
||||||
self = [super init];
|
|
||||||
if (self != nil) {
|
|
||||||
{{#isArrayModel}} _entriesBuilder = [[{{arrayModelType}}ManagedObjectBuilder alloc] init];
|
|
||||||
{{/isArrayModel}}{{#vars}}{{#complexType}}{{^isMapContainer}} _{{name}}Builder = [[{{complexType}}ManagedObjectBuilder alloc] init];
|
|
||||||
{{/isMapContainer}}{{/complexType}}{{/vars}} }
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
-({{classname}}ManagedObject*)createNew{{classname}}ManagedObjectInContext:(NSManagedObjectContext*)context {
|
|
||||||
{{classname}}ManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([{{classname}}ManagedObject class]) inManagedObjectContext:context];
|
|
||||||
return managedObject;
|
|
||||||
}
|
|
||||||
|
|
||||||
-({{classname}}ManagedObject*){{classname}}ManagedObjectFrom{{classname}}:({{classname}}*)object context:(NSManagedObjectContext*)context {
|
|
||||||
{{classname}}ManagedObject* new{{classname}} = [self createNew{{{classname}}}ManagedObjectInContext:context];
|
|
||||||
[self update{{classname}}ManagedObject:new{{classname}} with{{classname}}:object];
|
|
||||||
return new{{classname}};
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void)update{{classname}}ManagedObject:({{classname}}ManagedObject*)managedObject with{{classname}}:({{classname}}*)object {
|
|
||||||
if(!managedObject || !object) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
{{#vars}}{{^complexType}} managedObject.{{name}} = [object.{{name}} copy];{{/complexType}}{{#complexType}}{{#isListContainer}} if(object.{{name}}) {
|
|
||||||
NSMutableSet * convertedObjs = [NSMutableSet set];
|
|
||||||
for (id innerObject in object.{{name}}) {
|
|
||||||
id convertedObj = [self.{{name}}Builder {{complexType}}ManagedObjectFrom{{complexType}}:innerObject context:managedObject.managedObjectContext];
|
|
||||||
[convertedObjs addObject:convertedObj];
|
|
||||||
}
|
|
||||||
managedObject.{{name}} = convertedObjs;
|
|
||||||
}{{/isListContainer}}{{^isListContainer}}{{^isMapContainer}}
|
|
||||||
if(!managedObject.{{name}}) {
|
|
||||||
managedObject.{{name}} = [self.{{name}}Builder {{complexType}}ManagedObjectFrom{{complexType}}:object.{{name}} context:managedObject.managedObjectContext];
|
|
||||||
} else {
|
|
||||||
[self.{{name}}Builder update{{complexType}}ManagedObject:managedObject.{{name}} with{{complexType}}:object.{{name}}];
|
|
||||||
}{{/isMapContainer}}{{#isMapContainer}}managedObject.{{name}} = [object.{{name}} copy];{{/isMapContainer}}{{/isListContainer}}{{/complexType}}
|
|
||||||
{{/vars}}{{#isArrayModel}} NSMutableSet * convertedObjs = [NSMutableSet set];
|
|
||||||
for (id innerObject in object) {
|
|
||||||
id convertedObj = [self.entriesBuilder {{arrayModelType}}ManagedObjectFrom{{arrayModelType}}:innerObject context:managedObject.managedObjectContext];
|
|
||||||
[convertedObjs addObject:convertedObj];
|
|
||||||
}
|
|
||||||
managedObject.entries = convertedObjs;{{/isArrayModel}}
|
|
||||||
}
|
|
||||||
|
|
||||||
-({{classname}}*){{classname}}From{{classname}}ManagedObject:({{classname}}ManagedObject*)obj {
|
|
||||||
if(!obj) {
|
|
||||||
return nil;
|
|
||||||
}
|
|
||||||
{{classname}}* new{{classname}} = [[{{classname}} alloc] init];
|
|
||||||
[self update{{classname}}:new{{classname}} with{{classname}}ManagedObject:obj];
|
|
||||||
return new{{classname}};
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void)update{{classname}}:({{classname}}*)new{{classname}} with{{classname}}ManagedObject:({{classname}}ManagedObject*)obj {
|
|
||||||
{{#isArrayModel}} [new{{classname}} removeAllObjects];
|
|
||||||
NSMutableArray* convertedObjs = [NSMutableArray array];
|
|
||||||
for (id innerObject in obj.entries) {
|
|
||||||
id convertedObj = [self.entriesBuilder {{arrayModelType}}From{{arrayModelType}}ManagedObject:innerObject];
|
|
||||||
[convertedObjs addObject:convertedObj];
|
|
||||||
}
|
|
||||||
[new{{classname}} addObjectsFromArray:convertedObjs];
|
|
||||||
{{/isArrayModel}}{{#vars}}{{^complexType}} new{{classname}}.{{name}} = [obj.{{name}} copy];{{/complexType}}{{#complexType}}{{#isListContainer}} if(obj.{{name}} != nil) {
|
|
||||||
NSMutableArray* convertedObjs = [NSMutableArray array];
|
|
||||||
for (id innerObject in obj.{{name}}) {
|
|
||||||
id convertedObj = [self.{{name}}Builder {{complexType}}From{{complexType}}ManagedObject:innerObject];
|
|
||||||
[convertedObjs addObject:convertedObj];
|
|
||||||
}
|
|
||||||
new{{classname}}.{{name}} = ({{{ datatype }}})convertedObjs;
|
|
||||||
}
|
|
||||||
{{/isListContainer}}{{^isListContainer}} new{{classname}}.{{name}} = [self.{{name}}Builder {{complexType}}From{{complexType}}ManagedObject:obj.{{name}}];{{/isListContainer}}{{/complexType}}
|
|
||||||
{{/vars}}
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
||||||
{{/model}}
|
|
||||||
{{/models}}
|
|
@ -1,31 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <CoreData/CoreData.h>
|
|
||||||
|
|
||||||
{{#imports}}#import "{{import}}ManagedObjectBuilder.h"
|
|
||||||
{{/imports}}
|
|
||||||
{{#models}}
|
|
||||||
{{#model}}
|
|
||||||
|
|
||||||
#import "{{classname}}ManagedObject.h"
|
|
||||||
#import "{{classname}}.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classname}}ManagedObjectBuilder : NSObject
|
|
||||||
|
|
||||||
{{#isArrayModel}}@property (nonatomic, strong) {{arrayModelType}}ManagedObjectBuilder * entriesBuilder;{{/isArrayModel}}{{#vars}}{{#complexType}}@property (nonatomic, strong) {{complexType}}ManagedObjectBuilder * {{name}}Builder;
|
|
||||||
{{/complexType}}{{/vars}}
|
|
||||||
|
|
||||||
-({{classname}}ManagedObject*)createNew{{classname}}ManagedObjectInContext:(NSManagedObjectContext*)context;
|
|
||||||
|
|
||||||
-({{classname}}ManagedObject*){{classname}}ManagedObjectFrom{{classname}}:({{classname}}*)object context:(NSManagedObjectContext*)context;
|
|
||||||
|
|
||||||
-(void)update{{classname}}ManagedObject:({{classname}}ManagedObject*)object with{{classname}}:({{classname}}*)object2;
|
|
||||||
|
|
||||||
-({{classname}}*){{classname}}From{{classname}}ManagedObject:({{classname}}ManagedObject*)obj;
|
|
||||||
|
|
||||||
-(void)update{{classname}}:({{classname}}*)object with{{classname}}ManagedObject:({{classname}}ManagedObject*)object2;
|
|
||||||
|
|
||||||
@end
|
|
||||||
{{/model}}
|
|
||||||
{{/models}}
|
|
@ -1,42 +0,0 @@
|
|||||||
#import "{{classPrefix}}Object.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}Object
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Workaround for JSONModel multithreading issues
|
|
||||||
* https://github.com/icanzilb/JSONModel/issues/441
|
|
||||||
*/
|
|
||||||
- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err {
|
|
||||||
static NSMutableSet *classNames;
|
|
||||||
static dispatch_once_t onceToken;
|
|
||||||
dispatch_once(&onceToken, ^{
|
|
||||||
classNames = [NSMutableSet new];
|
|
||||||
});
|
|
||||||
|
|
||||||
BOOL initSync;
|
|
||||||
@synchronized([self class])
|
|
||||||
{
|
|
||||||
NSString *className = NSStringFromClass([self class]);
|
|
||||||
initSync = ![classNames containsObject:className];
|
|
||||||
if(initSync)
|
|
||||||
{
|
|
||||||
[classNames addObject:className];
|
|
||||||
self = [super initWithDictionary:dict error:err];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if(!initSync)
|
|
||||||
{
|
|
||||||
self = [super initWithDictionary:dict error:err];
|
|
||||||
}
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the string presentation of the object.
|
|
||||||
* This method will be called when logging model object using `NSLog`.
|
|
||||||
*/
|
|
||||||
- (NSString *)description {
|
|
||||||
return [[self toDictionary] description];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,8 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <JSONModel/JSONModel.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}Object : JSONModel
|
|
||||||
|
|
||||||
@end
|
|
@ -1,20 +0,0 @@
|
|||||||
#import "{{classPrefix}}QueryParamCollection.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}QueryParamCollection
|
|
||||||
|
|
||||||
@synthesize values = _values;
|
|
||||||
@synthesize format = _format;
|
|
||||||
|
|
||||||
- (id)initWithValuesAndFormat:(NSArray *)values
|
|
||||||
format:(NSString *)format {
|
|
||||||
|
|
||||||
self = [super init];
|
|
||||||
if (self) {
|
|
||||||
_values = values;
|
|
||||||
_format = format;
|
|
||||||
}
|
|
||||||
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,13 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}QueryParamCollection : NSObject
|
|
||||||
|
|
||||||
@property(nonatomic, readonly) NSArray* values;
|
|
||||||
@property(nonatomic, readonly) NSString* format;
|
|
||||||
|
|
||||||
- (id) initWithValuesAndFormat: (NSArray*) values
|
|
||||||
format: (NSString*) format;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,143 +0,0 @@
|
|||||||
# {{podName}}
|
|
||||||
|
|
||||||
{{#appDescription}}
|
|
||||||
{{{appDescription}}}
|
|
||||||
{{/appDescription}}
|
|
||||||
|
|
||||||
This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project:
|
|
||||||
|
|
||||||
- API version: {{appVersion}}
|
|
||||||
- Package version: {{artifactVersion}}
|
|
||||||
- Build date: {{generatedDate}}
|
|
||||||
- Build package: {{generatorClass}}
|
|
||||||
{{#infoUrl}}
|
|
||||||
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
|
|
||||||
{{/infoUrl}}
|
|
||||||
|
|
||||||
## Requirements
|
|
||||||
|
|
||||||
The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.com/questions/7778356/how-to-enable-disable-automatic-reference-counting) to be enabled in the Xcode project.
|
|
||||||
|
|
||||||
## Installation & Usage
|
|
||||||
### Install from Github using [CocoaPods](https://cocoapods.org/)
|
|
||||||
|
|
||||||
Add the following to the Podfile:
|
|
||||||
|
|
||||||
```ruby
|
|
||||||
pod '{{podName}}', :git => 'https://github.com/{{gitUserId}}/{{gitRepoId}}.git'
|
|
||||||
```
|
|
||||||
|
|
||||||
To specify a particular branch, append `, :branch => 'branch-name-here'`
|
|
||||||
|
|
||||||
To specify a particular commit, append `, :commit => '11aa22'`
|
|
||||||
|
|
||||||
### Install from local path using [CocoaPods](https://cocoapods.org/)
|
|
||||||
|
|
||||||
Put the SDK under your project folder (e.g. /path/to/objc_project/Vendor/{{podName}}) and then add the following to the Podfile:
|
|
||||||
|
|
||||||
```ruby
|
|
||||||
pod '{{podName}}', :path => 'Vendor/{{podName}}'
|
|
||||||
```
|
|
||||||
|
|
||||||
### Usage
|
|
||||||
|
|
||||||
Import the following:
|
|
||||||
|
|
||||||
```objc
|
|
||||||
#import <{{podName}}/{{{classPrefix}}}ApiClient.h>
|
|
||||||
#import <{{podName}}/{{{classPrefix}}}Configuration.h>
|
|
||||||
// load models
|
|
||||||
{{#models}}{{#model}}#import <{{podName}}/{{{classname}}}.h>
|
|
||||||
{{/model}}{{/models}}// load API classes for accessing endpoints
|
|
||||||
{{#apiInfo}}{{#apis}}#import <{{podName}}/{{{classname}}}.h>
|
|
||||||
{{/apis}}{{/apiInfo}}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Recommendation
|
|
||||||
|
|
||||||
It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue.
|
|
||||||
|
|
||||||
## Getting Started
|
|
||||||
|
|
||||||
Please follow the [installation procedure](#installation--usage) and then run the following:
|
|
||||||
|
|
||||||
```objc
|
|
||||||
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
|
|
||||||
{{#hasAuthMethods}}
|
|
||||||
{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig];
|
|
||||||
{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}})
|
|
||||||
[apiConfig setUsername:@"YOUR_USERNAME"];
|
|
||||||
[apiConfig setPassword:@"YOUR_PASSWORD"];
|
|
||||||
{{/isBasic}}{{#isApiKey}}
|
|
||||||
// Configure API key authorization: (authentication scheme: {{{name}}})
|
|
||||||
[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"];
|
|
||||||
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
|
|
||||||
//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"];
|
|
||||||
{{/isApiKey}}{{#isOAuth}}
|
|
||||||
// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}})
|
|
||||||
[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
|
|
||||||
{{/isOAuth}}{{/authMethods}}
|
|
||||||
{{/hasAuthMethods}}
|
|
||||||
|
|
||||||
{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
|
|
||||||
{{/allParams}}
|
|
||||||
|
|
||||||
{{classname}} *apiInstance = [[{{classname}} alloc] init];
|
|
||||||
|
|
||||||
{{#summary}}// {{{.}}}
|
|
||||||
{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
|
|
||||||
{{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}}
|
|
||||||
{{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) {
|
|
||||||
{{#returnType}}
|
|
||||||
if (output) {
|
|
||||||
NSLog(@"%@", output);
|
|
||||||
}
|
|
||||||
{{/returnType}}
|
|
||||||
if (error) {
|
|
||||||
NSLog(@"Error: %@", error);
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 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}}
|
|
||||||
|
|
@ -1,231 +0,0 @@
|
|||||||
#import "{{classPrefix}}ResponseDeserializer.h"
|
|
||||||
#import <JSONModel/JSONModel.h>
|
|
||||||
#import <ISO8601/ISO8601.h>
|
|
||||||
|
|
||||||
NSString *const {{classPrefix}}DeserializationErrorDomainKey = @"{{classPrefix}}DeserializationErrorDomainKey";
|
|
||||||
|
|
||||||
NSInteger const {{classPrefix}}TypeMismatchErrorCode = 143553;
|
|
||||||
|
|
||||||
NSInteger const {{classPrefix}}EmptyValueOccurredErrorCode = 143509;
|
|
||||||
|
|
||||||
NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
|
|
||||||
|
|
||||||
|
|
||||||
@interface {{classPrefix}}ResponseDeserializer ()
|
|
||||||
|
|
||||||
@property (nonatomic, strong) NSNumberFormatter* numberFormatter;
|
|
||||||
@property (nonatomic, strong) NSArray *primitiveTypes;
|
|
||||||
@property (nonatomic, strong) NSArray *basicReturnTypes;
|
|
||||||
|
|
||||||
@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression;
|
|
||||||
@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression;
|
|
||||||
@property (nonatomic, strong) NSRegularExpression* dictPatExpression;
|
|
||||||
@property (nonatomic, strong) NSRegularExpression* dictModelsPatExpression;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}ResponseDeserializer
|
|
||||||
|
|
||||||
- (instancetype)init {
|
|
||||||
self = [super init];
|
|
||||||
if (self) {
|
|
||||||
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
|
|
||||||
formatter.numberStyle = NSNumberFormatterDecimalStyle;
|
|
||||||
_numberFormatter = formatter;
|
|
||||||
_primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"];
|
|
||||||
_basicReturnTypes = @[@"NSObject", @"id", @"NSData"];
|
|
||||||
_arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>"
|
|
||||||
options:NSRegularExpressionCaseInsensitive
|
|
||||||
error:nil];
|
|
||||||
_arrayOfPrimitivesPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray\\* /\\* (.+) \\*/"
|
|
||||||
options:NSRegularExpressionCaseInsensitive
|
|
||||||
error:nil];
|
|
||||||
_dictPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSDictionary\\* /\\* (.+?), (.+) \\*/"
|
|
||||||
options:NSRegularExpressionCaseInsensitive
|
|
||||||
error:nil];
|
|
||||||
_dictModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSDictionary\\<(.+?), (.+)*\\>"
|
|
||||||
options:NSRegularExpressionCaseInsensitive
|
|
||||||
error:nil];
|
|
||||||
}
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Deserialize methods
|
|
||||||
|
|
||||||
- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error {
|
|
||||||
// return nil if data is nil or className is nil
|
|
||||||
if (!data || !className || [data isKindOfClass:[NSNull class]]) {
|
|
||||||
return nil;
|
|
||||||
}
|
|
||||||
|
|
||||||
// remove "*" from className, if ends with "*"
|
|
||||||
if ([className hasSuffix:@"*"]) {
|
|
||||||
className = [className substringToIndex:[className length] - 1];
|
|
||||||
}
|
|
||||||
// pure object
|
|
||||||
if ([self.basicReturnTypes containsObject:className]) {
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
// primitives
|
|
||||||
if ([self.primitiveTypes containsObject:className]) {
|
|
||||||
return [self deserializePrimitiveValue:data class:className error:error];
|
|
||||||
}
|
|
||||||
|
|
||||||
NSTextCheckingResult *match = nil;
|
|
||||||
NSRange range = NSMakeRange(0, [className length]);
|
|
||||||
// list of models
|
|
||||||
match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range];
|
|
||||||
if (match) {
|
|
||||||
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
|
||||||
return [self deserializeArrayValue:data innerType:innerType error:error];
|
|
||||||
}
|
|
||||||
|
|
||||||
// list of primitives
|
|
||||||
match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range];
|
|
||||||
if (match) {
|
|
||||||
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
|
|
||||||
return [self deserializeArrayValue:data innerType:innerType error:error];
|
|
||||||
}
|
|
||||||
|
|
||||||
// map
|
|
||||||
match = [self.dictPatExpression firstMatchInString:className options:0 range:range];
|
|
||||||
if (match) {
|
|
||||||
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
|
||||||
return [self deserializeDictionaryValue:data valueType:valueType error:error];
|
|
||||||
}
|
|
||||||
|
|
||||||
match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range];
|
|
||||||
if (match) {
|
|
||||||
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
|
|
||||||
return [self deserializeDictionaryValue:data valueType:valueType error:error];
|
|
||||||
}
|
|
||||||
|
|
||||||
// model
|
|
||||||
Class ModelClass = NSClassFromString(className);
|
|
||||||
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
|
|
||||||
return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error];
|
|
||||||
}
|
|
||||||
|
|
||||||
if(error) {
|
|
||||||
*error = [self unknownResponseErrorWithExpectedType:className data:data];
|
|
||||||
}
|
|
||||||
return nil;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (id) deserializeDictionaryValue:(id) data valueType:(NSString *) valueType error:(NSError**)error {
|
|
||||||
if(![data isKindOfClass: [NSDictionary class]]) {
|
|
||||||
if(error) {
|
|
||||||
*error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSDictionary class]) data:data];
|
|
||||||
}
|
|
||||||
return nil;
|
|
||||||
}
|
|
||||||
__block NSMutableDictionary *resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]];
|
|
||||||
for (id key in [data allKeys]) {
|
|
||||||
id obj = [data valueForKey:key];
|
|
||||||
id dicObj = [self deserialize:obj class:valueType error:error];
|
|
||||||
if(dicObj) {
|
|
||||||
[resultDict setValue:dicObj forKey:key];
|
|
||||||
} else if([obj isKindOfClass:[NSNull class]]) {
|
|
||||||
if(self.treatNullAsError) {
|
|
||||||
if (error) {
|
|
||||||
*error = [self emptyValueOccurredError];
|
|
||||||
}
|
|
||||||
resultDict = nil;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
resultDict = nil;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return resultDict;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (id) deserializeArrayValue:(id) data innerType:(NSString *) innerType error:(NSError**)error {
|
|
||||||
if(![data isKindOfClass: [NSArray class]]) {
|
|
||||||
if(error) {
|
|
||||||
*error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSArray class]) data:data];
|
|
||||||
}
|
|
||||||
return nil;
|
|
||||||
}
|
|
||||||
NSMutableArray* resultArray = [NSMutableArray arrayWithCapacity:[data count]];
|
|
||||||
for (id obj in data) {
|
|
||||||
id arrObj = [self deserialize:obj class:innerType error:error];
|
|
||||||
if(arrObj) {
|
|
||||||
[resultArray addObject:arrObj];
|
|
||||||
} else if([obj isKindOfClass:[NSNull class]]) {
|
|
||||||
if(self.treatNullAsError) {
|
|
||||||
if (error) {
|
|
||||||
*error = [self emptyValueOccurredError];
|
|
||||||
}
|
|
||||||
resultArray = nil;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
resultArray = nil;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return resultArray;
|
|
||||||
};
|
|
||||||
|
|
||||||
- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error {
|
|
||||||
if ([className isEqualToString:@"NSString"]) {
|
|
||||||
return [NSString stringWithString:data];
|
|
||||||
}
|
|
||||||
else if ([className isEqualToString:@"NSDate"]) {
|
|
||||||
return [self deserializeDateValue:data error:error];
|
|
||||||
}
|
|
||||||
else if ([className isEqualToString:@"NSNumber"]) {
|
|
||||||
// NSNumber from NSNumber
|
|
||||||
if ([data isKindOfClass:[NSNumber class]]) {
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
else if ([data isKindOfClass:[NSString class]]) {
|
|
||||||
// NSNumber (NSCFBoolean) from NSString
|
|
||||||
if ([[data lowercaseString] isEqualToString:@"true"] || [[data lowercaseString] isEqualToString:@"false"]) {
|
|
||||||
return @([data boolValue]);
|
|
||||||
// NSNumber from NSString
|
|
||||||
} else {
|
|
||||||
NSNumber* formattedValue = [self.numberFormatter numberFromString:data];
|
|
||||||
if(!formattedValue && [data length] > 0 && error) {
|
|
||||||
*error = [self typeMismatchErrorWithExpectedType:className data:data];
|
|
||||||
}
|
|
||||||
return formattedValue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if(error) {
|
|
||||||
*error = [self typeMismatchErrorWithExpectedType:className data:data];
|
|
||||||
}
|
|
||||||
return nil;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (id) deserializeDateValue:(id) data error:(NSError**)error {
|
|
||||||
NSDate *date =[NSDate dateWithISO8601String:data];
|
|
||||||
if(!date && [data length] > 0 && error) {
|
|
||||||
*error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSDate class]) data:data];
|
|
||||||
}
|
|
||||||
return date;
|
|
||||||
};
|
|
||||||
|
|
||||||
-(NSError *)typeMismatchErrorWithExpectedType:(NSString *)expected data:(id)data {
|
|
||||||
NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Received response [%@] is not an object of type %@",nil),data, expected];
|
|
||||||
NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message};
|
|
||||||
return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}TypeMismatchErrorCode userInfo:userInfo];
|
|
||||||
}
|
|
||||||
|
|
||||||
-(NSError *)emptyValueOccurredError {
|
|
||||||
NSString * message = NSLocalizedString(@"Received response contains null value in dictionary or array response",nil);
|
|
||||||
NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message};
|
|
||||||
return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}EmptyValueOccurredErrorCode userInfo:userInfo];
|
|
||||||
}
|
|
||||||
|
|
||||||
-(NSError *)unknownResponseErrorWithExpectedType:(NSString *)expected data:(id)data {
|
|
||||||
NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [reponse: %@]",nil),expected,data];
|
|
||||||
NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message};
|
|
||||||
return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}UnknownResponseObjectErrorCode userInfo:userInfo];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,46 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A key for deserialization ErrorDomain
|
|
||||||
*/
|
|
||||||
extern NSString *const {{classPrefix}}DeserializationErrorDomainKey;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Code for deserialization type mismatch error
|
|
||||||
*/
|
|
||||||
extern NSInteger const {{classPrefix}}TypeMismatchErrorCode;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Code for deserialization empty value error
|
|
||||||
*/
|
|
||||||
extern NSInteger const {{classPrefix}}EmptyValueOccurredErrorCode;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Error code for unknown response
|
|
||||||
*/
|
|
||||||
extern NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode;
|
|
||||||
|
|
||||||
@protocol {{classPrefix}}ResponseDeserializer <NSObject>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Deserializes the given data to Objective-C object.
|
|
||||||
*
|
|
||||||
* @param data The data will be deserialized.
|
|
||||||
* @param class The type of objective-c object.
|
|
||||||
* @param error The error
|
|
||||||
*/
|
|
||||||
- (id) deserialize:(id) data class:(NSString *) className error:(NSError**)error;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@interface {{classPrefix}}ResponseDeserializer : NSObject <{{classPrefix}}ResponseDeserializer>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* If an null value occurs in dictionary or array if set to YES whole response will be invalid else will be ignored
|
|
||||||
* @default NO
|
|
||||||
*/
|
|
||||||
@property (nonatomic, assign) BOOL treatNullAsError;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,168 +0,0 @@
|
|||||||
#import "{{classPrefix}}Sanitizer.h"
|
|
||||||
#import "{{classPrefix}}Object.h"
|
|
||||||
#import "{{classPrefix}}QueryParamCollection.h"
|
|
||||||
#import <ISO8601/ISO8601.h>
|
|
||||||
|
|
||||||
NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) {
|
|
||||||
static NSString * const k{{classPrefix}}CharactersGeneralDelimitersToEncode = @":#[]@";
|
|
||||||
static NSString * const k{{classPrefix}}CharactersSubDelimitersToEncode = @"!$&'()*+,;=";
|
|
||||||
|
|
||||||
NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
|
|
||||||
[allowedCharacterSet removeCharactersInString:[k{{classPrefix}}CharactersGeneralDelimitersToEncode stringByAppendingString:k{{classPrefix}}CharactersSubDelimitersToEncode]];
|
|
||||||
|
|
||||||
static NSUInteger const batchSize = 50;
|
|
||||||
|
|
||||||
NSUInteger index = 0;
|
|
||||||
NSMutableString *escaped = @"".mutableCopy;
|
|
||||||
|
|
||||||
while (index < string.length) {
|
|
||||||
#pragma GCC diagnostic push
|
|
||||||
#pragma GCC diagnostic ignored "-Wgnu"
|
|
||||||
NSUInteger length = MIN(string.length - index, batchSize);
|
|
||||||
#pragma GCC diagnostic pop
|
|
||||||
NSRange range = NSMakeRange(index, length);
|
|
||||||
|
|
||||||
// To avoid breaking up character sequences such as 👴🏻👮🏽
|
|
||||||
range = [string rangeOfComposedCharacterSequencesForRange:range];
|
|
||||||
|
|
||||||
NSString *substring = [string substringWithRange:range];
|
|
||||||
NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
|
|
||||||
[escaped appendString:encoded];
|
|
||||||
|
|
||||||
index += range.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
return escaped;
|
|
||||||
}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}Sanitizer ()
|
|
||||||
|
|
||||||
@property (nonatomic, strong) NSRegularExpression* jsonHeaderTypeExpression;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}Sanitizer
|
|
||||||
|
|
||||||
static NSString * kApplicationJSONType = @"application/json";
|
|
||||||
|
|
||||||
-(instancetype)init {
|
|
||||||
self = [super init];
|
|
||||||
if ( !self ) {
|
|
||||||
return nil;
|
|
||||||
}
|
|
||||||
_jsonHeaderTypeExpression = [NSRegularExpression regularExpressionWithPattern:@"(.*)application(.*)json(.*)" options:NSRegularExpressionCaseInsensitive error:nil];
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
- (id) sanitizeForSerialization:(id) object {
|
|
||||||
if (object == nil) {
|
|
||||||
return nil;
|
|
||||||
}
|
|
||||||
else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[{{classPrefix}}QueryParamCollection class]]) {
|
|
||||||
return object;
|
|
||||||
}
|
|
||||||
else if ([object isKindOfClass:[NSDate class]]) {
|
|
||||||
return [self dateParameterToString:object];
|
|
||||||
}
|
|
||||||
else if ([object isKindOfClass:[NSArray class]]) {
|
|
||||||
NSArray *objectArray = object;
|
|
||||||
NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]];
|
|
||||||
[object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
|
|
||||||
id sanitizedObj = [self sanitizeForSerialization:obj];
|
|
||||||
if (sanitizedObj) {
|
|
||||||
[sanitizedObjs addObject:sanitizedObj];
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
return sanitizedObjs;
|
|
||||||
}
|
|
||||||
else if ([object isKindOfClass:[NSDictionary class]]) {
|
|
||||||
NSDictionary *objectDict = object;
|
|
||||||
NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]];
|
|
||||||
[object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
|
||||||
id sanitizedObj = [self sanitizeForSerialization:obj];
|
|
||||||
if (sanitizedObj) {
|
|
||||||
sanitizedObjs[key] = sanitizedObj;
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
return sanitizedObjs;
|
|
||||||
}
|
|
||||||
else if ([object isKindOfClass:[{{classPrefix}}Object class]]) {
|
|
||||||
return [object toDictionary];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
NSException *e = [NSException
|
|
||||||
exceptionWithName:@"InvalidObjectArgumentException"
|
|
||||||
reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object]
|
|
||||||
userInfo:nil];
|
|
||||||
@throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSString *) parameterToString:(id)param {
|
|
||||||
if ([param isKindOfClass:[NSString class]]) {
|
|
||||||
return param;
|
|
||||||
}
|
|
||||||
else if ([param isKindOfClass:[NSNumber class]]) {
|
|
||||||
return [param stringValue];
|
|
||||||
}
|
|
||||||
else if ([param isKindOfClass:[NSDate class]]) {
|
|
||||||
return [self dateParameterToString:param];
|
|
||||||
}
|
|
||||||
else if ([param isKindOfClass:[NSArray class]]) {
|
|
||||||
NSMutableArray *mutableParam = [NSMutableArray array];
|
|
||||||
[param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
|
|
||||||
[mutableParam addObject:[self parameterToString:obj]];
|
|
||||||
}];
|
|
||||||
return [mutableParam componentsJoinedByString:@","];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
NSException *e = [NSException
|
|
||||||
exceptionWithName:@"InvalidObjectArgumentException"
|
|
||||||
reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param]
|
|
||||||
userInfo:nil];
|
|
||||||
@throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSString *)dateParameterToString:(id)param {
|
|
||||||
return [param ISO8601String];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Utility Methods
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Detect `Accept` from accepts
|
|
||||||
*/
|
|
||||||
- (NSString *) selectHeaderAccept:(NSArray *)accepts {
|
|
||||||
if (accepts.count == 0) {
|
|
||||||
return @"";
|
|
||||||
}
|
|
||||||
NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]];
|
|
||||||
for (NSString *string in accepts) {
|
|
||||||
if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) {
|
|
||||||
return kApplicationJSONType;
|
|
||||||
}
|
|
||||||
[lowerAccepts addObject:[string lowercaseString]];
|
|
||||||
}
|
|
||||||
return [lowerAccepts componentsJoinedByString:@", "];
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Detect `Content-Type` from contentTypes
|
|
||||||
*/
|
|
||||||
- (NSString *) selectHeaderContentType:(NSArray *)contentTypes {
|
|
||||||
if (contentTypes.count == 0) {
|
|
||||||
return kApplicationJSONType;
|
|
||||||
}
|
|
||||||
NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]];
|
|
||||||
for (NSString *string in contentTypes) {
|
|
||||||
if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){
|
|
||||||
return kApplicationJSONType;
|
|
||||||
}
|
|
||||||
[lowerContentTypes addObject:[string lowercaseString]];
|
|
||||||
}
|
|
||||||
return [lowerContentTypes firstObject];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,45 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
extern NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string);
|
|
||||||
|
|
||||||
@protocol {{classPrefix}}Sanitizer <NSObject>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sanitize object for request
|
|
||||||
*
|
|
||||||
* @param object The query/path/header/form/body param to be sanitized.
|
|
||||||
*/
|
|
||||||
- (id) sanitizeForSerialization:(id) object;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert parameter to NSString
|
|
||||||
*/
|
|
||||||
- (NSString *) parameterToString: (id) param;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Detects Accept header from accepts NSArray
|
|
||||||
*
|
|
||||||
* @param accepts NSArray of header
|
|
||||||
*
|
|
||||||
* @return The Accept header
|
|
||||||
*/
|
|
||||||
-(NSString *) selectHeaderAccept:(NSArray *)accepts;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Detects Content-Type header from contentTypes NSArray
|
|
||||||
*
|
|
||||||
* @param contentTypes NSArray of header
|
|
||||||
*
|
|
||||||
* @return The Content-Type header
|
|
||||||
*/
|
|
||||||
-(NSString *) selectHeaderContentType:(NSArray *)contentTypes;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@interface {{classPrefix}}Sanitizer : NSObject <{{classPrefix}}Sanitizer>
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@end
|
|
@ -1,160 +0,0 @@
|
|||||||
{{#operations}}
|
|
||||||
#import "{{classname}}.h"
|
|
||||||
#import "{{classPrefix}}QueryParamCollection.h"
|
|
||||||
{{#imports}}#import "{{import}}.h"
|
|
||||||
{{/imports}}
|
|
||||||
{{newline}}
|
|
||||||
|
|
||||||
@interface {{classname}} ()
|
|
||||||
|
|
||||||
@property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@implementation {{classname}}
|
|
||||||
|
|
||||||
NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain";
|
|
||||||
NSInteger k{{classname}}MissingParamErrorCode = 234513;
|
|
||||||
|
|
||||||
@synthesize apiSessionManager = _apiSessionManager;
|
|
||||||
|
|
||||||
#pragma mark - Initialize methods
|
|
||||||
|
|
||||||
-(instancetype) initWithApiSessionManager:({{classPrefix}}ApiSessionManager *)apiSessionManager {
|
|
||||||
self = [super init];
|
|
||||||
if (self) {
|
|
||||||
_apiSessionManager = apiSessionManager;
|
|
||||||
_defaultHeaders = [NSMutableDictionary dictionary];
|
|
||||||
}
|
|
||||||
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark -
|
|
||||||
|
|
||||||
-(NSString*) defaultHeaderForKey:(NSString*)key {
|
|
||||||
return self.defaultHeaders[key];
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
|
|
||||||
[self setDefaultHeaderValue:value forKey:key];
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key {
|
|
||||||
[self.defaultHeaders setValue:value forKey:key];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Api Methods
|
|
||||||
|
|
||||||
{{#operation}}
|
|
||||||
///
|
|
||||||
/// {{{summary}}}
|
|
||||||
/// {{{notes}}}
|
|
||||||
/// {{#allParams}} @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
|
|
||||||
///
|
|
||||||
/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
|
|
||||||
///
|
|
||||||
-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
|
|
||||||
{{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}}
|
|
||||||
{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler {
|
|
||||||
{{#allParams}}
|
|
||||||
{{#required}}
|
|
||||||
// verify the required parameter '{{paramName}}' is set
|
|
||||||
if ({{paramName}} == nil) {
|
|
||||||
NSParameterAssert({{paramName}});
|
|
||||||
if(handler) {
|
|
||||||
NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"{{paramName}}"] };
|
|
||||||
NSError* error = [NSError errorWithDomain:k{{classname}}ErrorDomain code:k{{classname}}MissingParamErrorCode userInfo:userInfo];
|
|
||||||
handler({{#returnType}}nil, {{/returnType}}error);
|
|
||||||
}
|
|
||||||
return nil;
|
|
||||||
}
|
|
||||||
|
|
||||||
{{/required}}
|
|
||||||
{{/allParams}}
|
|
||||||
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"];
|
|
||||||
|
|
||||||
// remove format in URL if needed
|
|
||||||
[resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)];
|
|
||||||
|
|
||||||
NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init];
|
|
||||||
{{#pathParams}}
|
|
||||||
if ({{paramName}} != nil) {
|
|
||||||
pathParams[@"{{baseName}}"] = {{paramName}};
|
|
||||||
}
|
|
||||||
{{/pathParams}}
|
|
||||||
|
|
||||||
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
|
|
||||||
{{#queryParams}}
|
|
||||||
if ({{paramName}} != nil) {
|
|
||||||
{{#collectionFormat}}
|
|
||||||
queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{paramName}} format: @"{{collectionFormat}}"];
|
|
||||||
{{/collectionFormat}}
|
|
||||||
{{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}}
|
|
||||||
}
|
|
||||||
{{/queryParams}}
|
|
||||||
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiSessionManager.configuration.defaultHeaders];
|
|
||||||
[headerParams addEntriesFromDictionary:self.defaultHeaders];
|
|
||||||
{{#headerParams}}
|
|
||||||
if ({{paramName}} != nil) {
|
|
||||||
headerParams[@"{{baseName}}"] = {{paramName}};
|
|
||||||
}
|
|
||||||
{{/headerParams}}
|
|
||||||
// HTTP header `Accept`
|
|
||||||
NSString *acceptHeader = [self.apiSessionManager.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]];
|
|
||||||
if(acceptHeader.length > 0) {
|
|
||||||
headerParams[@"Accept"] = acceptHeader;
|
|
||||||
}
|
|
||||||
|
|
||||||
// response content type
|
|
||||||
NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @"";
|
|
||||||
|
|
||||||
// request content type
|
|
||||||
NSString *requestContentType = [self.apiSessionManager.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]];
|
|
||||||
|
|
||||||
// Authentication setting
|
|
||||||
NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}];
|
|
||||||
|
|
||||||
id bodyParam = nil;
|
|
||||||
NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init];
|
|
||||||
NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init];
|
|
||||||
{{#bodyParam}}
|
|
||||||
bodyParam = {{paramName}};
|
|
||||||
{{/bodyParam}}
|
|
||||||
{{^bodyParam}}
|
|
||||||
{{#formParams}}
|
|
||||||
{{#notFile}}
|
|
||||||
if ({{paramName}}) {
|
|
||||||
formParams[@"{{baseName}}"] = {{paramName}};
|
|
||||||
}
|
|
||||||
{{/notFile}}
|
|
||||||
{{#isFile}}
|
|
||||||
localVarFiles[@"{{paramName}}"] = {{paramName}};
|
|
||||||
{{/isFile}}
|
|
||||||
{{/formParams}}
|
|
||||||
{{/bodyParam}}
|
|
||||||
|
|
||||||
return [self.apiSessionManager requestWithPath: resourcePath
|
|
||||||
method: @"{{httpMethod}}"
|
|
||||||
pathParams: pathParams
|
|
||||||
queryParams: queryParams
|
|
||||||
formParams: formParams
|
|
||||||
files: localVarFiles
|
|
||||||
body: bodyParam
|
|
||||||
headerParams: headerParams
|
|
||||||
authSettings: authSettings
|
|
||||||
requestContentType: requestContentType
|
|
||||||
responseContentType: responseContentType
|
|
||||||
responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}}
|
|
||||||
completionBlock: ^(id data, NSError *error) {
|
|
||||||
if(handler) {
|
|
||||||
handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error);
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
|
|
||||||
{{/operation}}
|
|
||||||
|
|
||||||
{{newline}}
|
|
||||||
{{/operations}}
|
|
||||||
@end
|
|
@ -1,32 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
{{#imports}}#import "{{import}}.h"
|
|
||||||
{{/imports}}
|
|
||||||
#import "{{classPrefix}}Api.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
|
|
||||||
@interface {{classname}}: NSObject <{{classPrefix}}Api>
|
|
||||||
|
|
||||||
extern NSString* k{{classname}}ErrorDomain;
|
|
||||||
extern NSInteger k{{classname}}MissingParamErrorCode;
|
|
||||||
|
|
||||||
{{#operations}}
|
|
||||||
{{#operation}}
|
|
||||||
/// {{{summary}}}
|
|
||||||
/// {{#notes}}{{{notes}}}{{/notes}}
|
|
||||||
///
|
|
||||||
/// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
|
|
||||||
/// {{/allParams}}{{#responses}}
|
|
||||||
/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}}
|
|
||||||
///
|
|
||||||
/// @return {{{returnType}}}
|
|
||||||
-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
|
|
||||||
{{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}}
|
|
||||||
{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler;
|
|
||||||
|
|
||||||
{{newline}}
|
|
||||||
{{/operation}}
|
|
||||||
{{/operations}}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,18 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import "{{classPrefix}}Object.h"
|
|
||||||
#import "{{classPrefix}}ApiSessionManager.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@protocol {{classPrefix}}Api <NSObject>
|
|
||||||
|
|
||||||
@property(readonly, nonatomic, strong) {{classPrefix}}ApiSessionManager *apiSessionManager;
|
|
||||||
|
|
||||||
-(instancetype) initWithApiSessionManager:({{classPrefix}}ApiSessionManager *)apiSessionManager;
|
|
||||||
|
|
||||||
-(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:");
|
|
||||||
|
|
||||||
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key;
|
|
||||||
-(NSString*) defaultHeaderForKey:(NSString*)key;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,85 +0,0 @@
|
|||||||
# {{classname}}{{#description}}
|
|
||||||
{{description}}{{/description}}
|
|
||||||
|
|
||||||
All URIs are relative to *{{basePath}}*
|
|
||||||
|
|
||||||
Method | HTTP request | Description
|
|
||||||
------------- | ------------- | -------------
|
|
||||||
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
|
|
||||||
{{/operation}}{{/operations}}
|
|
||||||
|
|
||||||
{{#operations}}
|
|
||||||
{{#operation}}
|
|
||||||
# **{{{operationId}}}**
|
|
||||||
```objc
|
|
||||||
-(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
|
|
||||||
{{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}}
|
|
||||||
{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler;
|
|
||||||
```
|
|
||||||
|
|
||||||
{{{summary}}}{{#notes}}
|
|
||||||
|
|
||||||
{{{notes}}}{{/notes}}
|
|
||||||
|
|
||||||
### Example
|
|
||||||
```objc
|
|
||||||
{{#hasAuthMethods}}
|
|
||||||
{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig];
|
|
||||||
{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}})
|
|
||||||
[apiConfig setUsername:@"YOUR_USERNAME"];
|
|
||||||
[apiConfig setPassword:@"YOUR_PASSWORD"];
|
|
||||||
{{/isBasic}}{{#isApiKey}}
|
|
||||||
// Configure API key authorization: (authentication scheme: {{{name}}})
|
|
||||||
[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"];
|
|
||||||
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
|
|
||||||
//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"];
|
|
||||||
{{/isApiKey}}{{#isOAuth}}
|
|
||||||
// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}})
|
|
||||||
[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
|
|
||||||
{{/isOAuth}}{{/authMethods}}
|
|
||||||
{{/hasAuthMethods}}
|
|
||||||
|
|
||||||
{{#allParams}}{{{dataType}}} {{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
|
|
||||||
{{/allParams}}
|
|
||||||
|
|
||||||
{{classname}}*apiInstance = [[{{classname}} alloc] init];
|
|
||||||
|
|
||||||
{{#summary}}// {{{.}}}
|
|
||||||
{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
|
|
||||||
{{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}}
|
|
||||||
{{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) {
|
|
||||||
{{#returnType}}
|
|
||||||
if (output) {
|
|
||||||
NSLog(@"%@", output);
|
|
||||||
}
|
|
||||||
{{/returnType}}
|
|
||||||
if (error) {
|
|
||||||
NSLog(@"Error calling {{classname}}->{{operationId}}: %@", error);
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
```
|
|
||||||
|
|
||||||
### Parameters
|
|
||||||
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
|
|
||||||
Name | Type | Description | Notes
|
|
||||||
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}
|
|
||||||
{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}
|
|
||||||
{{/allParams}}
|
|
||||||
|
|
||||||
### Return type
|
|
||||||
|
|
||||||
{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}}
|
|
||||||
|
|
||||||
### Authorization
|
|
||||||
|
|
||||||
{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}}
|
|
||||||
|
|
||||||
### HTTP request headers
|
|
||||||
|
|
||||||
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
|
|
||||||
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
|
|
||||||
|
|
||||||
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
|
|
||||||
|
|
||||||
{{/operation}}
|
|
||||||
{{/operations}}
|
|
@ -1,52 +0,0 @@
|
|||||||
#!/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'
|
|
||||||
|
|
@ -1,53 +0,0 @@
|
|||||||
# 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
|
|
||||||
|
|
||||||
# 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
|
|
@ -1,23 +0,0 @@
|
|||||||
/**
|
|
||||||
* {{{appName}}}
|
|
||||||
* {{{appDescription}}}
|
|
||||||
*
|
|
||||||
* {{#version}}OpenAPI spec version: {{{version}}}{{/version}}
|
|
||||||
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
|
|
||||||
*
|
|
||||||
* NOTE: This class is auto generated by the swagger code generator program.
|
|
||||||
* https://github.com/swagger-api/swagger-codegen.git
|
|
||||||
* Do not edit the class manually.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
@ -1,59 +0,0 @@
|
|||||||
{{#models}}
|
|
||||||
{{#model}}
|
|
||||||
#import "{{classname}}.h"
|
|
||||||
|
|
||||||
@implementation {{classname}}
|
|
||||||
|
|
||||||
- (instancetype)init {
|
|
||||||
self = [super init];
|
|
||||||
if (self) {
|
|
||||||
// initialize property's default value, if any
|
|
||||||
{{#vars}}{{#defaultValue}}self.{{name}} = {{{defaultValue}}};
|
|
||||||
{{/defaultValue}}{{/vars}}
|
|
||||||
}
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
{{#vars}}{{^vendorExtensions.x-unique-id-key}}{{/vendorExtensions.x-unique-id-key}}{{#vendorExtensions.x-unique-id-key}}
|
|
||||||
-(NSString*)indexPropertyName {
|
|
||||||
return @"{{name}}";
|
|
||||||
}
|
|
||||||
{{/vendorExtensions.x-unique-id-key}}{{/vars}}
|
|
||||||
{{#discriminator}}
|
|
||||||
/**
|
|
||||||
* Maps "discriminator" value to the sub-class name, so that inheritance is supported.
|
|
||||||
*/
|
|
||||||
- (id)initWithDictionary:(NSDictionary *)dict error:(NSError *__autoreleasing *)err {
|
|
||||||
NSString * discriminatedClassName = [dict valueForKey:@"{{discriminator}}"];
|
|
||||||
if(discriminatedClassName == nil ){
|
|
||||||
return [super initWithDictionary:dict error:err];
|
|
||||||
}
|
|
||||||
Class class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:discriminatedClassName]);
|
|
||||||
if([self class ] == class) {
|
|
||||||
return [super initWithDictionary:dict error:err];
|
|
||||||
}
|
|
||||||
return [[class alloc] initWithDictionary:dict error: err];
|
|
||||||
}
|
|
||||||
{{/discriminator}}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Maps json key to property name.
|
|
||||||
* This method is used by `JSONModel`.
|
|
||||||
*/
|
|
||||||
+ (JSONKeyMapper *)keyMapper {
|
|
||||||
return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Indicates whether the property with the given name is optional.
|
|
||||||
* If `propertyName` is optional, then return `YES`, otherwise return `NO`.
|
|
||||||
* This method is used by `JSONModel`.
|
|
||||||
*/
|
|
||||||
+ (BOOL)propertyIsOptional:(NSString *)propertyName {
|
|
||||||
|
|
||||||
NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}];
|
|
||||||
return [optionalProperties containsObject:propertyName];
|
|
||||||
}
|
|
||||||
|
|
||||||
{{/model}}
|
|
||||||
@end
|
|
||||||
{{/models}}
|
|
@ -1,25 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import "{{classPrefix}}Object.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
{{#imports}}#import "{{import}}.h"
|
|
||||||
{{/imports}}
|
|
||||||
{{newline}}
|
|
||||||
{{#models}}
|
|
||||||
{{#model}}
|
|
||||||
|
|
||||||
@protocol {{classname}}
|
|
||||||
@end
|
|
||||||
|
|
||||||
@interface {{classname}} : {{#parent}}{{{parent}}}{{/parent}}{{^parent}}{{classPrefix}}Object{{/parent}}
|
|
||||||
|
|
||||||
{{#vars}}
|
|
||||||
{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}}
|
|
||||||
*/{{/description}}
|
|
||||||
@property(nonatomic) {{{ datatype }}} {{name}};
|
|
||||||
{{/vars}}
|
|
||||||
|
|
||||||
@end
|
|
||||||
{{/model}}
|
|
||||||
{{/models}}
|
|
@ -1,11 +0,0 @@
|
|||||||
{{#models}}{{#model}}# {{classname}}
|
|
||||||
|
|
||||||
## Properties
|
|
||||||
Name | Type | Description | Notes
|
|
||||||
------------ | ------------- | ------------- | -------------
|
|
||||||
{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}}
|
|
||||||
{{/vars}}
|
|
||||||
|
|
||||||
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
|
||||||
|
|
||||||
{{/model}}{{/models}}
|
|
@ -1,37 +0,0 @@
|
|||||||
#
|
|
||||||
# Be sure to run `pod lib lint {{podName}}.podspec' to ensure this is a
|
|
||||||
# valid spec and remove all comments before submitting the spec.
|
|
||||||
#
|
|
||||||
# Any lines starting with a # are optional, but encouraged
|
|
||||||
#
|
|
||||||
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
|
|
||||||
#
|
|
||||||
|
|
||||||
Pod::Spec.new do |s|
|
|
||||||
s.name = "{{podName}}"
|
|
||||||
s.version = "{{podVersion}}"
|
|
||||||
{{#apiInfo}}{{#apis}}{{^hasMore}}
|
|
||||||
s.summary = "{{appName}}"
|
|
||||||
s.description = <<-DESC
|
|
||||||
{{{appDescription}}}
|
|
||||||
DESC
|
|
||||||
{{/hasMore}}{{/apis}}{{/apiInfo}}
|
|
||||||
s.platform = :ios, '7.0'
|
|
||||||
s.requires_arc = true
|
|
||||||
|
|
||||||
{{^useCoreData}}s.framework = 'SystemConfiguration'{{/useCoreData}}{{#useCoreData}}s.frameworks = 'SystemConfiguration', 'CoreData'{{/useCoreData}}
|
|
||||||
|
|
||||||
s.homepage = "{{gitRepoURL}}"
|
|
||||||
s.license = "{{#license}}{{license}}{{/license}}{{^license}}Apache License, Version 2.0{{/license}}"
|
|
||||||
s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" }
|
|
||||||
s.author = { "{{authorName}}" => "{{authorEmail}}" }
|
|
||||||
|
|
||||||
s.source_files = '{{podName}}/**/*.{m,h}'
|
|
||||||
s.public_header_files = '{{podName}}/**/*.h'
|
|
||||||
{{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}}
|
|
||||||
|
|
||||||
s.dependency 'AFNetworking', '~> 3'
|
|
||||||
s.dependency 'JSONModel', '~> 1.2'
|
|
||||||
s.dependency 'ISO8601', '~> 0.6'
|
|
||||||
end
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
||||||
<plist version="1.0">
|
|
||||||
<dict>
|
|
||||||
<key>_XCCurrentVersionName</key>
|
|
||||||
<string>{{classPrefix}}Model.xcdatamodel</string>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
@ -1,74 +0,0 @@
|
|||||||
# Swagger Codegen for the ObjcSessionManagerClientCodegen library
|
|
||||||
|
|
||||||
## Overview
|
|
||||||
This is a boiler-plate project to generate your own client library with Swagger. It's goal is
|
|
||||||
to get you started with the basic plumbing so you can put in your own logic. It won't work without
|
|
||||||
your changes applied.
|
|
||||||
|
|
||||||
## What's Swagger?
|
|
||||||
The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service.
|
|
||||||
|
|
||||||
|
|
||||||
Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more.
|
|
||||||
|
|
||||||
## How do I use this?
|
|
||||||
At this point, you've likely generated a client setup. It will include something along these lines:
|
|
||||||
|
|
||||||
```
|
|
||||||
.
|
|
||||||
|- README.md // this file
|
|
||||||
|- pom.xml // build script
|
|
||||||
|-- src
|
|
||||||
|--- main
|
|
||||||
|---- java
|
|
||||||
|----- io.swagger.codegen.languages.ObjcsessionmanagerclientcodegenGenerator.java // generator file
|
|
||||||
|---- resources
|
|
||||||
|----- ObjcSessionManagerClientCodegen // template files
|
|
||||||
|----- META-INF
|
|
||||||
|------ services
|
|
||||||
|------- io.swagger.codegen.CodegenConfig
|
|
||||||
```
|
|
||||||
|
|
||||||
You _will_ need to make changes in at least the following:
|
|
||||||
|
|
||||||
`ObjcsessionmanagerclientcodegenGenerator.java`
|
|
||||||
|
|
||||||
Templates in this folder:
|
|
||||||
|
|
||||||
`src/main/resources/ObjcSessionManagerClientCodegen`
|
|
||||||
|
|
||||||
Once modified, you can run this:
|
|
||||||
|
|
||||||
```
|
|
||||||
mvn package
|
|
||||||
```
|
|
||||||
|
|
||||||
In your generator project. A single jar file will be produced in `target`. You can now use that with codegen:
|
|
||||||
|
|
||||||
```
|
|
||||||
java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManagerClientCodegen -o ./test
|
|
||||||
```
|
|
||||||
|
|
||||||
Now your templates are available to the client generator and you can write output values
|
|
||||||
|
|
||||||
## But how do I modify this?
|
|
||||||
The `ObjcsessionmanagerclientcodegenGenerator.java` has comments in it--lots of comments. There is no good substitute
|
|
||||||
for reading the code more, though. See how the `ObjcsessionmanagerclientcodegenGenerator` implements `CodegenConfig`.
|
|
||||||
That class has the signature of all values that can be overridden.
|
|
||||||
|
|
||||||
For the templates themselves, you have a number of values available to you for generation.
|
|
||||||
You can execute the `java` command from above while passing different debug flags to show
|
|
||||||
the object you have available during client generation:
|
|
||||||
|
|
||||||
```
|
|
||||||
# The following additional debug options are available for all codegen targets:
|
|
||||||
# -DdebugSwagger prints the OpenAPI Specification as interpreted by the codegen
|
|
||||||
# -DdebugModels prints models passed to the template engine
|
|
||||||
# -DdebugOperations prints operations passed to the template engine
|
|
||||||
# -DdebugSupportingFiles prints additional data passed to the template engine
|
|
||||||
|
|
||||||
java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManagerClientCodegen -o ./test
|
|
||||||
```
|
|
||||||
|
|
||||||
Will, for example, output the debug info for operations. You can use this info
|
|
||||||
in the `api.mustache` file.
|
|
@ -1,102 +0,0 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>io.swagger</groupId>
|
|
||||||
<artifactId>ObjcSessionManager-swagger-codegen</artifactId>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
<name>ObjcSessionManager-swagger-codegen</name>
|
|
||||||
<version>1.0.0</version>
|
|
||||||
<prerequisites>
|
|
||||||
<maven>2.2.0</maven>
|
|
||||||
</prerequisites>
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>2.12</version>
|
|
||||||
<configuration>
|
|
||||||
<systemProperties>
|
|
||||||
<property>
|
|
||||||
<name>loggerPath</name>
|
|
||||||
<value>conf/log4j.properties</value>
|
|
||||||
</property>
|
|
||||||
</systemProperties>
|
|
||||||
<argLine>-Xms512m -Xmx1500m</argLine>
|
|
||||||
<parallel>methods</parallel>
|
|
||||||
<forkMode>pertest</forkMode>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
|
|
||||||
<!-- attach test jar -->
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-jar-plugin</artifactId>
|
|
||||||
<version>2.2</version>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<goals>
|
|
||||||
<goal>jar</goal>
|
|
||||||
<goal>test-jar</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
<configuration>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.codehaus.mojo</groupId>
|
|
||||||
<artifactId>build-helper-maven-plugin</artifactId>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>add_sources</id>
|
|
||||||
<phase>generate-sources</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>add-source</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<sources>
|
|
||||||
<source>src/main/java</source>
|
|
||||||
</sources>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
<execution>
|
|
||||||
<id>add_test_sources</id>
|
|
||||||
<phase>generate-test-sources</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>add-test-source</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<sources>
|
|
||||||
<source>src/test/java</source>
|
|
||||||
</sources>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<version>2.3.2</version>
|
|
||||||
<configuration>
|
|
||||||
<source>1.6</source>
|
|
||||||
<target>1.6</target>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>io.swagger</groupId>
|
|
||||||
<artifactId>swagger-codegen</artifactId>
|
|
||||||
<version>${swagger-codegen-version}</version>
|
|
||||||
<scope>provided</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
<properties>
|
|
||||||
<swagger-codegen-version>2.2.0-SNAPSHOT</swagger-codegen-version>
|
|
||||||
<maven-plugin-version>1.0.0</maven-plugin-version>
|
|
||||||
<junit-version>4.8.1</junit-version>
|
|
||||||
</properties>
|
|
||||||
</project>
|
|
@ -1,750 +0,0 @@
|
|||||||
package io.swagger.codegen.languages;
|
|
||||||
|
|
||||||
import io.swagger.codegen.*;
|
|
||||||
import io.swagger.models.ArrayModel;
|
|
||||||
import io.swagger.models.Model;
|
|
||||||
import io.swagger.models.properties.*;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
public class ObjcSessionManagerClientCodegen extends DefaultCodegen implements CodegenConfig {
|
|
||||||
public static final String CLASS_PREFIX = "classPrefix";
|
|
||||||
public static final String POD_NAME = "podName";
|
|
||||||
public static final String AUTHOR_NAME = "authorName";
|
|
||||||
public static final String AUTHOR_EMAIL = "authorEmail";
|
|
||||||
public static final String LICENSE = "license";
|
|
||||||
public static final String GIT_REPO_URL = "gitRepoURL";
|
|
||||||
public static final String DEFAULT_LICENSE = "Apache License, Version 2.0";
|
|
||||||
public static final String CORE_DATA = "coreData";
|
|
||||||
|
|
||||||
protected Set<String> foundationClasses = new HashSet<String>();
|
|
||||||
protected String podName = "SwaggerClient";
|
|
||||||
protected String podVersion = "1.0.0";
|
|
||||||
protected String classPrefix = "SWG";
|
|
||||||
protected String authorName = "Swagger";
|
|
||||||
protected String authorEmail = "apiteam@swagger.io";
|
|
||||||
protected String license = DEFAULT_LICENSE;
|
|
||||||
protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen";
|
|
||||||
protected String[] specialWords = {"new", "copy"};
|
|
||||||
protected String apiDocPath = "docs/";
|
|
||||||
protected String modelDocPath = "docs/";
|
|
||||||
protected String modelFilesPath = "Model/";
|
|
||||||
protected String coreFilesPath = "Core/";
|
|
||||||
protected String apiFilesPath = "Api/";
|
|
||||||
|
|
||||||
protected boolean generateCoreData = false;
|
|
||||||
|
|
||||||
protected Set<String> advancedMapingTypes = new HashSet<String>();
|
|
||||||
|
|
||||||
public ObjcSessionManagerClientCodegen() {
|
|
||||||
super();
|
|
||||||
|
|
||||||
outputFolder = "generated-code" + File.separator + "objcSessionManager";
|
|
||||||
modelTemplateFiles.put("model-header.mustache", ".h");
|
|
||||||
modelTemplateFiles.put("model-body.mustache", ".m");
|
|
||||||
apiTemplateFiles.put("api-header.mustache", ".h");
|
|
||||||
apiTemplateFiles.put("api-body.mustache", ".m");
|
|
||||||
embeddedTemplateDir = templateDir = "objcSessionManager";
|
|
||||||
modelDocTemplateFiles.put("model_doc.mustache", ".md");
|
|
||||||
apiDocTemplateFiles.put("api_doc.mustache", ".md");
|
|
||||||
|
|
||||||
defaultIncludes.clear();
|
|
||||||
defaultIncludes.add("bool");
|
|
||||||
defaultIncludes.add("BOOL");
|
|
||||||
defaultIncludes.add("int");
|
|
||||||
defaultIncludes.add("NSURL");
|
|
||||||
defaultIncludes.add("NSString");
|
|
||||||
defaultIncludes.add("NSObject");
|
|
||||||
defaultIncludes.add("NSArray");
|
|
||||||
defaultIncludes.add("NSNumber");
|
|
||||||
defaultIncludes.add("NSDate");
|
|
||||||
defaultIncludes.add("NSDictionary");
|
|
||||||
defaultIncludes.add("NSMutableArray");
|
|
||||||
defaultIncludes.add("NSMutableDictionary");
|
|
||||||
defaultIncludes.add("NSManagedObject");
|
|
||||||
defaultIncludes.add("NSData");
|
|
||||||
|
|
||||||
advancedMapingTypes.add("NSDictionary");
|
|
||||||
advancedMapingTypes.add("NSArray");
|
|
||||||
advancedMapingTypes.add("NSMutableArray");
|
|
||||||
advancedMapingTypes.add("NSMutableDictionary");
|
|
||||||
advancedMapingTypes.add("NSObject");
|
|
||||||
advancedMapingTypes.add("NSNumber");
|
|
||||||
advancedMapingTypes.add("NSURL");
|
|
||||||
advancedMapingTypes.add("NSString");
|
|
||||||
advancedMapingTypes.add("NSDate");
|
|
||||||
|
|
||||||
languageSpecificPrimitives.clear();
|
|
||||||
languageSpecificPrimitives.add("NSNumber");
|
|
||||||
languageSpecificPrimitives.add("NSString");
|
|
||||||
languageSpecificPrimitives.add("NSObject");
|
|
||||||
languageSpecificPrimitives.add("NSDate");
|
|
||||||
languageSpecificPrimitives.add("NSData");
|
|
||||||
languageSpecificPrimitives.add("NSURL");
|
|
||||||
languageSpecificPrimitives.add("bool");
|
|
||||||
languageSpecificPrimitives.add("BOOL");
|
|
||||||
|
|
||||||
typeMapping.clear();
|
|
||||||
typeMapping.put("enum", "NSString");
|
|
||||||
typeMapping.put("date", "NSDate");
|
|
||||||
typeMapping.put("datetime", "NSDate");
|
|
||||||
typeMapping.put("boolean", "NSNumber");
|
|
||||||
typeMapping.put("string", "NSString");
|
|
||||||
typeMapping.put("integer", "NSNumber");
|
|
||||||
typeMapping.put("int", "NSNumber");
|
|
||||||
typeMapping.put("float", "NSNumber");
|
|
||||||
typeMapping.put("long", "NSNumber");
|
|
||||||
typeMapping.put("double", "NSNumber");
|
|
||||||
typeMapping.put("array", "NSArray");
|
|
||||||
typeMapping.put("map", "NSDictionary");
|
|
||||||
typeMapping.put("number", "NSNumber");
|
|
||||||
typeMapping.put("bigdecimal", "NSNumber");
|
|
||||||
typeMapping.put("List", "NSArray");
|
|
||||||
typeMapping.put("object", "NSObject");
|
|
||||||
typeMapping.put("file", "NSURL");
|
|
||||||
typeMapping.put("binary", "NSData");
|
|
||||||
typeMapping.put("bytearray", "NSData");
|
|
||||||
typeMapping.put("byte", "NSData");
|
|
||||||
typeMapping.put("uuid", "NSString");
|
|
||||||
typeMapping.put("password", "NSString");
|
|
||||||
|
|
||||||
// ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm
|
|
||||||
setReservedWordsLowerCase(
|
|
||||||
Arrays.asList(
|
|
||||||
// local variable names in API methods (endpoints)
|
|
||||||
"resourcePath", "pathParams", "queryParams", "headerParams",
|
|
||||||
"responseContentType", "requestContentType", "authSettings",
|
|
||||||
"formParams", "localVarFiles", "bodyParam",
|
|
||||||
// objc reserved words
|
|
||||||
"auto", "else", "long", "switch",
|
|
||||||
"break", "enum", "register", "typedef",
|
|
||||||
"case", "extern", "return", "union",
|
|
||||||
"char", "float", "short", "unsigned",
|
|
||||||
"const", "for", "signed", "void",
|
|
||||||
"continue", "goto", "sizeof", "volatile",
|
|
||||||
"default", "if", "id", "static", "while",
|
|
||||||
"do", "int", "struct", "_Packed",
|
|
||||||
"double", "protocol", "interface", "implementation",
|
|
||||||
"NSObject", "NSInteger", "NSNumber", "CGFloat",
|
|
||||||
"property", "nonatomic", "retain", "strong",
|
|
||||||
"weak", "unsafe_unretained", "readwrite", "readonly",
|
|
||||||
"description"
|
|
||||||
));
|
|
||||||
|
|
||||||
importMapping = new HashMap<String, String>();
|
|
||||||
|
|
||||||
foundationClasses = new HashSet<String>(
|
|
||||||
Arrays.asList(
|
|
||||||
"NSNumber",
|
|
||||||
"NSObject",
|
|
||||||
"NSString",
|
|
||||||
"NSDate",
|
|
||||||
"NSData",
|
|
||||||
"NSURL",
|
|
||||||
"NSDictionary")
|
|
||||||
);
|
|
||||||
|
|
||||||
instantiationTypes.put("array", "NSMutableArray");
|
|
||||||
instantiationTypes.put("map", "NSMutableDictionary");
|
|
||||||
|
|
||||||
cliOptions.clear();
|
|
||||||
cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models").defaultValue("false"));
|
|
||||||
cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`")
|
|
||||||
.defaultValue("SWG"));
|
|
||||||
cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).")
|
|
||||||
.defaultValue("SwaggerClient"));
|
|
||||||
cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version.")
|
|
||||||
.defaultValue("1.0.0"));
|
|
||||||
cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.").defaultValue("Swagger"));
|
|
||||||
cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io"));
|
|
||||||
cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.")
|
|
||||||
.defaultValue("https://github.com/swagger-api/swagger-codegen"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CodegenType getTag() {
|
|
||||||
return CodegenType.CLIENT;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getName() {
|
|
||||||
return "objc";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getHelp() {
|
|
||||||
return "Generates an Objective-C client library.";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void processOpts() {
|
|
||||||
super.processOpts();
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(POD_NAME)) {
|
|
||||||
setPodName((String) additionalProperties.get(POD_NAME));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(CodegenConstants.POD_VERSION)) {
|
|
||||||
setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(CORE_DATA)) {
|
|
||||||
Object coreData = additionalProperties.get(CORE_DATA);
|
|
||||||
if(((String)coreData).equalsIgnoreCase("true")) {
|
|
||||||
generateCoreData = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (additionalProperties.containsKey(CLASS_PREFIX)) {
|
|
||||||
setClassPrefix((String) additionalProperties.get(CLASS_PREFIX));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(AUTHOR_NAME)) {
|
|
||||||
setAuthorName((String) additionalProperties.get(AUTHOR_NAME));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(AUTHOR_EMAIL)) {
|
|
||||||
setAuthorEmail((String) additionalProperties.get(AUTHOR_EMAIL));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(GIT_REPO_URL)) {
|
|
||||||
setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL));
|
|
||||||
}
|
|
||||||
|
|
||||||
if(generateCoreData) {
|
|
||||||
modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h");
|
|
||||||
modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m");
|
|
||||||
modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h");
|
|
||||||
modelTemplateFiles.put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m");
|
|
||||||
}
|
|
||||||
|
|
||||||
additionalProperties.put(POD_NAME, podName);
|
|
||||||
additionalProperties.put(CodegenConstants.POD_VERSION, podVersion);
|
|
||||||
additionalProperties.put(CLASS_PREFIX, classPrefix);
|
|
||||||
additionalProperties.put(AUTHOR_NAME, authorName);
|
|
||||||
additionalProperties.put(AUTHOR_EMAIL, authorEmail);
|
|
||||||
additionalProperties.put(GIT_REPO_URL, gitRepoURL);
|
|
||||||
additionalProperties.put(LICENSE, license);
|
|
||||||
|
|
||||||
// make api and model doc path available in mustache template
|
|
||||||
additionalProperties.put("apiDocPath", apiDocPath);
|
|
||||||
additionalProperties.put("modelDocPath", modelDocPath);
|
|
||||||
additionalProperties.put("useCoreData", generateCoreData);
|
|
||||||
|
|
||||||
modelPackage = podName;
|
|
||||||
apiPackage = podName;
|
|
||||||
|
|
||||||
supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec"));
|
|
||||||
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
|
|
||||||
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); // !!
|
|
||||||
|
|
||||||
if(generateCoreData) {
|
|
||||||
supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion"));
|
|
||||||
supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// is apiclient
|
|
||||||
//supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", swaggerFolder, classPrefix + "ApiSessionManager.h"));
|
|
||||||
//supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", swaggerFolder, classPrefix + "ApiSessionManager.m"));
|
|
||||||
|
|
||||||
// protocol!
|
|
||||||
//supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", swaggerFolder, classPrefix + "Configuration.h"));
|
|
||||||
//supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.m"));
|
|
||||||
//supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.h"));
|
|
||||||
|
|
||||||
// missing!
|
|
||||||
//supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.h"));
|
|
||||||
//supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.m"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toInstantiationType(Property p) {
|
|
||||||
if (p instanceof MapProperty) {
|
|
||||||
return instantiationTypes.get("map");
|
|
||||||
} else if (p instanceof ArrayProperty) {
|
|
||||||
return instantiationTypes.get("array");
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getTypeDeclaration(String name) {
|
|
||||||
if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) {
|
|
||||||
return name;
|
|
||||||
} else {
|
|
||||||
return name + "*";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getSwaggerType(Property p) {
|
|
||||||
String swaggerType = super.getSwaggerType(p);
|
|
||||||
String type = null;
|
|
||||||
if (typeMapping.containsKey(swaggerType.toLowerCase())) {
|
|
||||||
type = typeMapping.get(swaggerType.toLowerCase());
|
|
||||||
if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) {
|
|
||||||
return toModelNameWithoutReservedWordCheck(type);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
type = swaggerType;
|
|
||||||
}
|
|
||||||
return toModelNameWithoutReservedWordCheck(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getTypeDeclaration(Property p) {
|
|
||||||
if (p instanceof ArrayProperty) {
|
|
||||||
ArrayProperty ap = (ArrayProperty) p;
|
|
||||||
Property inner = ap.getItems();
|
|
||||||
String innerTypeDeclaration = getTypeDeclaration(inner);
|
|
||||||
if (innerTypeDeclaration.endsWith("*")) {
|
|
||||||
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
|
|
||||||
}
|
|
||||||
// In this condition, type of property p is array of primitive,
|
|
||||||
// return container type with pointer, e.g. `NSArray*<NSString*>*'
|
|
||||||
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
|
|
||||||
return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
|
|
||||||
}
|
|
||||||
// In this condition, type of property p is array of model,
|
|
||||||
// return container type combine inner type with pointer, e.g. `NSArray<SWGTag>*'
|
|
||||||
else {
|
|
||||||
for (String sd : advancedMapingTypes) {
|
|
||||||
if(innerTypeDeclaration.startsWith(sd)) {
|
|
||||||
return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
|
|
||||||
}
|
|
||||||
} else if (p instanceof MapProperty) {
|
|
||||||
MapProperty mp = (MapProperty) p;
|
|
||||||
Property inner = mp.getAdditionalProperties();
|
|
||||||
|
|
||||||
String innerTypeDeclaration = getTypeDeclaration(inner);
|
|
||||||
|
|
||||||
if (innerTypeDeclaration.endsWith("*")) {
|
|
||||||
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
|
|
||||||
}
|
|
||||||
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
|
|
||||||
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + "*>*";
|
|
||||||
} else {
|
|
||||||
for (String s : advancedMapingTypes) {
|
|
||||||
if(innerTypeDeclaration.startsWith(s)) {
|
|
||||||
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + "*>*";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + ">*";
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
String swaggerType = getSwaggerType(p);
|
|
||||||
// In this condition, type of p is objective-c primitive type, e.g. `NSSNumber',
|
|
||||||
// return type of p with pointer, e.g. `NSNumber*'
|
|
||||||
if (languageSpecificPrimitives.contains(swaggerType) &&
|
|
||||||
foundationClasses.contains(swaggerType)) {
|
|
||||||
return swaggerType + "*";
|
|
||||||
}
|
|
||||||
// In this condition, type of p is c primitive type, e.g. `bool',
|
|
||||||
// return type of p, e.g. `bool'
|
|
||||||
else if (languageSpecificPrimitives.contains(swaggerType)) {
|
|
||||||
return swaggerType;
|
|
||||||
}
|
|
||||||
// In this condition, type of p is objective-c object type, e.g. `SWGPet',
|
|
||||||
// return type of p with pointer, e.g. `SWGPet*'
|
|
||||||
else {
|
|
||||||
return swaggerType + "*";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isDataTypeBinary(String dataType) {
|
|
||||||
return dataType.toLowerCase().startsWith("nsdata");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toModelName(String type) {
|
|
||||||
// model name cannot use reserved keyword
|
|
||||||
if (reservedWords.contains(type)) {
|
|
||||||
LOGGER.warn(type+ " (reserved word) cannot be used as model name. Renamed to " + ("model_" + type) + " before further processing");
|
|
||||||
type = "model_" + type; // e.g. return => ModelReturn (after camelize)
|
|
||||||
}
|
|
||||||
|
|
||||||
// model name starts with number
|
|
||||||
/* no need for the fix below as objc model starts with prefix (e.g. SWG)
|
|
||||||
if (type.matches("^\\d.*")) {
|
|
||||||
LOGGER.warn(type + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + type));
|
|
||||||
type = "model_" + type; // e.g. 200Response => Model200Response (after camelize)
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
return toModelNameWithoutReservedWordCheck(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Convert input to proper model name according to ObjC style guide
|
|
||||||
* without checking for reserved words
|
|
||||||
*
|
|
||||||
* @param type Model anme
|
|
||||||
* @return model Name in ObjC style guide
|
|
||||||
*/
|
|
||||||
public String toModelNameWithoutReservedWordCheck(String type) {
|
|
||||||
type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
|
|
||||||
|
|
||||||
// language build-in classes
|
|
||||||
if (typeMapping.keySet().contains(type) ||
|
|
||||||
foundationClasses.contains(type) ||
|
|
||||||
importMapping.values().contains(type) ||
|
|
||||||
defaultIncludes.contains(type) ||
|
|
||||||
languageSpecificPrimitives.contains(type)) {
|
|
||||||
return camelize(type);
|
|
||||||
}
|
|
||||||
// custom classes
|
|
||||||
else {
|
|
||||||
if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix
|
|
||||||
type = type + "_" + modelNameSuffix;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!StringUtils.isEmpty(modelNamePrefix)) { // set model prefix
|
|
||||||
type = modelNamePrefix + "_" + type;
|
|
||||||
}
|
|
||||||
|
|
||||||
return classPrefix + camelize(type); // add class prefix
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toModelFilename(String name) {
|
|
||||||
// should be the same as the model name
|
|
||||||
return toModelName(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void setNonArrayMapProperty(CodegenProperty property, String type) {
|
|
||||||
super.setNonArrayMapProperty(property, type);
|
|
||||||
if ("NSDictionary".equals(type)) {
|
|
||||||
property.setter = "initWithDictionary";
|
|
||||||
} else {
|
|
||||||
property.setter = "initWithValues";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toModelImport(String name) {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String apiDocFileFolder() {
|
|
||||||
return (outputFolder + "/" + apiDocPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String modelDocFileFolder() {
|
|
||||||
return (outputFolder + "/" + modelDocPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toModelDocFilename(String name) {
|
|
||||||
return toModelName(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toApiDocFilename(String name) {
|
|
||||||
return toApiName(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String apiFileFolder() {
|
|
||||||
return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String modelFileFolder() {
|
|
||||||
return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String coreFileFolder() {
|
|
||||||
return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toApiName(String name) {
|
|
||||||
return classPrefix + camelize(name) + "Api";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toApiFilename(String name) {
|
|
||||||
return classPrefix + camelize(name) + "Api";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toVarName(String name) {
|
|
||||||
// sanitize name
|
|
||||||
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
|
|
||||||
|
|
||||||
// if it's all upper case, do noting
|
|
||||||
if (name.matches("^[A-Z_]$")) {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
// if name starting with special word, escape with '_'
|
|
||||||
for(int i =0; i < specialWords.length; i++) {
|
|
||||||
if (name.matches("(?i:^" + specialWords[i] + ".*)"))
|
|
||||||
name = escapeSpecialWord(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
// camelize (lower first character) the variable name
|
|
||||||
// e.g. `pet_id` to `petId`
|
|
||||||
name = camelize(name, true);
|
|
||||||
|
|
||||||
// for reserved word or word starting with number, prepend `_`
|
|
||||||
if (isReservedWord(name) || name.matches("^\\d.*")) {
|
|
||||||
name = escapeReservedWord(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toParamName(String name) {
|
|
||||||
// should be the same as variable name
|
|
||||||
return toVarName(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String escapeReservedWord(String name) {
|
|
||||||
return "_" + name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("static-method")
|
|
||||||
public String escapeSpecialWord(String name) {
|
|
||||||
return "var_" + name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toOperationId(String operationId) {
|
|
||||||
// throw exception if method name is empty
|
|
||||||
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)) {
|
|
||||||
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true));
|
|
||||||
operationId = "call_" + operationId;
|
|
||||||
}
|
|
||||||
|
|
||||||
return camelize(sanitizeName(operationId), true);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setClassPrefix(String classPrefix) {
|
|
||||||
this.classPrefix = classPrefix;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPodName(String podName) {
|
|
||||||
this.podName = podName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPodVersion(String podVersion) {
|
|
||||||
this.podVersion = podVersion;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAuthorEmail(String authorEmail) {
|
|
||||||
this.authorEmail = authorEmail;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAuthorName(String authorName) {
|
|
||||||
this.authorName = authorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setGitRepoURL(String gitRepoURL) {
|
|
||||||
this.gitRepoURL = gitRepoURL;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setLicense(String license) {
|
|
||||||
this.license = license;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
|
|
||||||
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
|
|
||||||
if (operations != null) {
|
|
||||||
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
|
|
||||||
for (CodegenOperation operation : ops) {
|
|
||||||
if (!operation.allParams.isEmpty()) {
|
|
||||||
String firstParamName = operation.allParams.get(0).paramName;
|
|
||||||
operation.vendorExtensions.put("firstParamAltName", camelize(firstParamName));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return objs;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void postProcessModelProperty(CodegenModel model, CodegenProperty property){
|
|
||||||
super.postProcessModelProperty(model,property);
|
|
||||||
property.vendorExtensions.put("x-uppercaseName", camelize(property.name));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return the default value of the property
|
|
||||||
*
|
|
||||||
* @param p Swagger property object
|
|
||||||
* @return string presentation of the default value of the property
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public String toDefaultValue(Property p) {
|
|
||||||
if (p instanceof StringProperty) {
|
|
||||||
StringProperty dp = (StringProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@\"" + dp.getDefault().toString() + "\"";
|
|
||||||
}
|
|
||||||
} else if (p instanceof BooleanProperty) {
|
|
||||||
BooleanProperty dp = (BooleanProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
if (dp.getDefault().toString().equalsIgnoreCase("false"))
|
|
||||||
return "@0";
|
|
||||||
else
|
|
||||||
return "@1";
|
|
||||||
}
|
|
||||||
} else if (p instanceof DateProperty) {
|
|
||||||
// TODO
|
|
||||||
} else if (p instanceof DateTimeProperty) {
|
|
||||||
// TODO
|
|
||||||
} else if (p instanceof DoubleProperty) {
|
|
||||||
DoubleProperty dp = (DoubleProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@" + dp.getDefault().toString();
|
|
||||||
}
|
|
||||||
} else if (p instanceof FloatProperty) {
|
|
||||||
FloatProperty dp = (FloatProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@" + dp.getDefault().toString();
|
|
||||||
}
|
|
||||||
} else if (p instanceof IntegerProperty) {
|
|
||||||
IntegerProperty dp = (IntegerProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@" + dp.getDefault().toString();
|
|
||||||
}
|
|
||||||
} else if (p instanceof LongProperty) {
|
|
||||||
LongProperty dp = (LongProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@" + dp.getDefault().toString();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setParameterExampleValue(CodegenParameter p) {
|
|
||||||
String example;
|
|
||||||
|
|
||||||
if (p.defaultValue == null) {
|
|
||||||
example = p.example;
|
|
||||||
} else {
|
|
||||||
example = p.defaultValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
String type = p.baseType;
|
|
||||||
if (type == null) {
|
|
||||||
type = p.dataType;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ("NSString*".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = p.paramName + "_example";
|
|
||||||
}
|
|
||||||
example = "@\"" + escapeText(example) + "\"";
|
|
||||||
} else if ("NSNumber*".equals(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "56";
|
|
||||||
}
|
|
||||||
example = "@" + example;
|
|
||||||
/* OBJC uses NSNumber to represent both int, long, double and float
|
|
||||||
} else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "3.4";
|
|
||||||
} */
|
|
||||||
} else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "True";
|
|
||||||
}
|
|
||||||
} else if ("NSURL*".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "/path/to/file";
|
|
||||||
}
|
|
||||||
//[NSURL fileURLWithPath:@"path/to/file"]
|
|
||||||
example = "[NSURL fileURLWithPath:@\"" + escapeText(example) + "\"]";
|
|
||||||
/*} else if ("NSDate".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "2013-10-20";
|
|
||||||
}
|
|
||||||
example = "'" + escapeText(example) + "'";*/
|
|
||||||
} else if ("NSDate*".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "2013-10-20T19:20:30+01:00";
|
|
||||||
}
|
|
||||||
example = "@\"" + escapeText(example) + "\"";
|
|
||||||
} else if (!languageSpecificPrimitives.contains(type)) {
|
|
||||||
// type is a model class, e.g. User
|
|
||||||
type = type.replace("*", "");
|
|
||||||
// e.g. [[SWGPet alloc] init
|
|
||||||
example = "[[" + type + " alloc] init]";
|
|
||||||
} else {
|
|
||||||
LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (example == null) {
|
|
||||||
example = "NULL";
|
|
||||||
} else if (Boolean.TRUE.equals(p.isListContainer)) {
|
|
||||||
example = "@[" + example + "]";
|
|
||||||
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
|
|
||||||
example = "@{@\"key\" : " + example + "}";
|
|
||||||
}
|
|
||||||
|
|
||||||
p.example = example;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String escapeQuotationMark(String input) {
|
|
||||||
// remove " to avoid code injection
|
|
||||||
return input.replace("\"", "");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String escapeUnsafeCharacters(String input) {
|
|
||||||
return input.replace("*/", "*_/").replace("/*", "/_*");
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
io.swagger.codegen.languages.ObjcSessionManagerClientCodegen
|
|
@ -1,461 +0,0 @@
|
|||||||
#import <ISO8601/NSDate+ISO8601.h>
|
|
||||||
|
|
||||||
#import "{{classPrefix}}ApiSessionManager.h"
|
|
||||||
#import "{{classPrefix}}JSONRequestSerializer.h"
|
|
||||||
#import "{{classPrefix}}JSONResponseSerializer.h"
|
|
||||||
#import "{{classPrefix}}QueryParamCollection.h"
|
|
||||||
#import "{{classPrefix}}Object.h"
|
|
||||||
#import "{{classPrefix}}DefaultConfiguration.h"
|
|
||||||
|
|
||||||
|
|
||||||
NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject";
|
|
||||||
|
|
||||||
|
|
||||||
static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) {
|
|
||||||
NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response);
|
|
||||||
if(!headers[@"Content-Disposition"]) {
|
|
||||||
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
|
|
||||||
}
|
|
||||||
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
|
|
||||||
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
|
|
||||||
options:NSRegularExpressionCaseInsensitive
|
|
||||||
error:nil];
|
|
||||||
NSString *contentDispositionHeader = headers[@"Content-Disposition"];
|
|
||||||
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
|
|
||||||
options:0
|
|
||||||
range:NSMakeRange(0, [contentDispositionHeader length])];
|
|
||||||
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@interface {{classPrefix}}ApiSessionManager ()
|
|
||||||
|
|
||||||
@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}ApiSessionManager
|
|
||||||
|
|
||||||
- (instancetype)init {
|
|
||||||
|
|
||||||
return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (instancetype)initWithBaseURL:(NSURL *)url {
|
|
||||||
|
|
||||||
return [self initWithBaseURL:url
|
|
||||||
configuration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]];
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration {
|
|
||||||
|
|
||||||
return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (instancetype)initWithBaseURL:(NSURL *)url
|
|
||||||
configuration:(id<{{classPrefix}}Configuration>)configuration {
|
|
||||||
|
|
||||||
self = [super initWithBaseURL:url];
|
|
||||||
if (self) {
|
|
||||||
_configuration = configuration;
|
|
||||||
}
|
|
||||||
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Setter Methods
|
|
||||||
|
|
||||||
+ (void) setOfflineState:(BOOL) state {
|
|
||||||
offlineState = state;
|
|
||||||
}
|
|
||||||
|
|
||||||
+ (void) setCacheEnabled:(BOOL)enabled {
|
|
||||||
cacheEnabled = enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status {
|
|
||||||
reachabilityStatus = status;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey {
|
|
||||||
[self.requestSerializer setValue:value forHTTPHeaderField:forKey];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)setRequestSerializer:(AFHTTPRequestSerializer<AFURLRequestSerialization> *)requestSerializer {
|
|
||||||
[super setRequestSerializer:requestSerializer];
|
|
||||||
requestSerializer.timeoutInterval = self.timeoutInterval;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Cache Methods
|
|
||||||
|
|
||||||
+(void)clearCache {
|
|
||||||
[[NSURLCache sharedURLCache] removeAllCachedResponses];
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize
|
|
||||||
diskSize: (unsigned long) diskSize {
|
|
||||||
NSAssert(memorySize > 0, @"invalid in-memory cache size");
|
|
||||||
NSAssert(diskSize >= 0, @"invalid disk cache size");
|
|
||||||
|
|
||||||
NSURLCache *cache =
|
|
||||||
[[NSURLCache alloc]
|
|
||||||
initWithMemoryCapacity:memorySize
|
|
||||||
diskCapacity:diskSize
|
|
||||||
diskPath:@"swagger_url_cache"];
|
|
||||||
|
|
||||||
[NSURLCache setSharedURLCache:cache];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Reachability Methods
|
|
||||||
|
|
||||||
+(AFNetworkReachabilityStatus) getReachabilityStatus {
|
|
||||||
return reachabilityStatus;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(BOOL) getOfflineState {
|
|
||||||
return offlineState;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock {
|
|
||||||
reachabilityChangeBlock = changeBlock;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) configureCacheReachibility {
|
|
||||||
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
|
|
||||||
reachabilityStatus = status;
|
|
||||||
{{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status));
|
|
||||||
[{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable];
|
|
||||||
|
|
||||||
// call the reachability block, if configured
|
|
||||||
if (reachabilityChangeBlock != nil) {
|
|
||||||
reachabilityChangeBlock(status);
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
|
|
||||||
[self.reachabilityManager startMonitoring];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Task Methods
|
|
||||||
|
|
||||||
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request
|
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
|
||||||
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
|
|
||||||
{{classPrefix}}DebugLogResponse(response, responseObject,request,error);
|
|
||||||
|
|
||||||
if(!error) {
|
|
||||||
completionBlock(responseObject, nil);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
|
|
||||||
if (responseObject) {
|
|
||||||
// Add in the (parsed) response body.
|
|
||||||
userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject;
|
|
||||||
}
|
|
||||||
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
|
||||||
completionBlock(nil, augmentedError);
|
|
||||||
}];
|
|
||||||
|
|
||||||
return task;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSURLSessionDownloadTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request
|
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
|
||||||
id<{{classPrefix}}Configuration> config = self.configuration;
|
|
||||||
|
|
||||||
NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
|
||||||
{{classPrefix}}DebugLogResponse(response, responseObject,request,error);
|
|
||||||
|
|
||||||
if(error) {
|
|
||||||
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
|
|
||||||
if (responseObject) {
|
|
||||||
userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject;
|
|
||||||
}
|
|
||||||
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
|
||||||
completionBlock(nil, augmentedError);
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory();
|
|
||||||
NSString *filename = {{classPrefix}}__fileNameForResponse(response);
|
|
||||||
|
|
||||||
NSString *filepath = [directory stringByAppendingPathComponent:filename];
|
|
||||||
NSURL *file = [NSURL fileURLWithPath:filepath];
|
|
||||||
|
|
||||||
[responseObject writeToURL:file atomically:YES];
|
|
||||||
|
|
||||||
completionBlock(file, nil);
|
|
||||||
}];
|
|
||||||
|
|
||||||
return task;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Perform Request Methods
|
|
||||||
|
|
||||||
- (NSURLSessionTask*) requestWithPath: (NSString*) path
|
|
||||||
method: (NSString*) method
|
|
||||||
pathParams: (NSDictionary *) pathParams
|
|
||||||
queryParams: (NSDictionary*) queryParams
|
|
||||||
formParams: (NSDictionary *) formParams
|
|
||||||
files: (NSDictionary *) files
|
|
||||||
body: (id) body
|
|
||||||
headerParams: (NSDictionary*) headerParams
|
|
||||||
authSettings: (NSArray *) authSettings
|
|
||||||
requestContentType: (NSString*) requestContentType
|
|
||||||
responseContentType: (NSString*) responseContentType
|
|
||||||
responseType: (NSString *) responseType
|
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
|
||||||
// setting request serializer
|
|
||||||
if ([requestContentType isEqualToString:@"application/json"]) {
|
|
||||||
self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else if ([requestContentType isEqualToString:@"multipart/form-data"]) {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
NSAssert(NO, @"Unsupported request type %@", requestContentType);
|
|
||||||
}
|
|
||||||
|
|
||||||
// setting response serializer
|
|
||||||
if ([responseContentType isEqualToString:@"application/json"]) {
|
|
||||||
self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer];
|
|
||||||
} else {
|
|
||||||
self.responseSerializer = [AFHTTPResponseSerializer serializer];
|
|
||||||
}
|
|
||||||
|
|
||||||
// sanitize parameters
|
|
||||||
pathParams = [self.sanitizer sanitizeForSerialization:pathParams];
|
|
||||||
queryParams = [self.sanitizer sanitizeForSerialization:queryParams];
|
|
||||||
headerParams = [self.sanitizer sanitizeForSerialization:headerParams];
|
|
||||||
formParams = [self.sanitizer sanitizeForSerialization:formParams];
|
|
||||||
if(![body isKindOfClass:[NSData class]]) {
|
|
||||||
body = [self.sanitizer sanitizeForSerialization:body];
|
|
||||||
}
|
|
||||||
|
|
||||||
// auth setting
|
|
||||||
[self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings];
|
|
||||||
|
|
||||||
NSMutableString *resourcePath = [NSMutableString stringWithString:path];
|
|
||||||
[pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
|
||||||
NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj];
|
|
||||||
safeString = {{classPrefix}}PercentEscapedStringFromString(safeString);
|
|
||||||
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
|
|
||||||
}];
|
|
||||||
|
|
||||||
NSMutableURLRequest * request = nil;
|
|
||||||
|
|
||||||
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
|
|
||||||
if ([pathWithQueryParams hasPrefix:@"/"]) {
|
|
||||||
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
|
|
||||||
if (files.count > 0) {
|
|
||||||
__weak __typeof(self)weakSelf = self;
|
|
||||||
request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
|
|
||||||
URLString:urlString
|
|
||||||
parameters:nil
|
|
||||||
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
|
|
||||||
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
|
||||||
NSString *objString = [weakSelf.sanitizer parameterToString:obj];
|
|
||||||
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
|
|
||||||
[formData appendPartWithFormData:data name:key];
|
|
||||||
}];
|
|
||||||
[files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
|
||||||
NSURL *filePath = (NSURL *)obj;
|
|
||||||
[formData appendPartWithFileURL:filePath name:key error:nil];
|
|
||||||
}];
|
|
||||||
} error:nil];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if (formParams) {
|
|
||||||
request = [self.requestSerializer requestWithMethod:method
|
|
||||||
URLString:urlString
|
|
||||||
parameters:formParams
|
|
||||||
error:nil];
|
|
||||||
}
|
|
||||||
if (body) {
|
|
||||||
request = [self.requestSerializer requestWithMethod:method
|
|
||||||
URLString:urlString
|
|
||||||
parameters:body
|
|
||||||
error:nil];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// request cache
|
|
||||||
BOOL hasHeaderParams = [headerParams count] > 0;
|
|
||||||
if (offlineState) {
|
|
||||||
{{classPrefix}}DebugLog(@"%@ cache forced", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
|
|
||||||
}
|
|
||||||
else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) {
|
|
||||||
{{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
{{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasHeaderParams){
|
|
||||||
for(NSString * key in [headerParams keyEnumerator]){
|
|
||||||
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
|
|
||||||
|
|
||||||
[self postProcessRequest:request];
|
|
||||||
|
|
||||||
|
|
||||||
NSURLSessionTask *task = nil
|
|
||||||
|
|
||||||
if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) {
|
|
||||||
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
|
||||||
completionBlock(data, error);
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
[self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
|
||||||
NSError * serializationError;
|
|
||||||
id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError];
|
|
||||||
if(!response && !error){
|
|
||||||
error = serializationError;
|
|
||||||
}
|
|
||||||
completionBlock(response, error);
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
|
|
||||||
[task resume];
|
|
||||||
|
|
||||||
return task;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Added for easier override to modify request
|
|
||||||
- (void)postProcessRequest:(NSMutableURLRequest *)request {
|
|
||||||
// Always disable cookies!
|
|
||||||
[request setHTTPShouldHandleCookies:NO];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark -
|
|
||||||
|
|
||||||
- (NSString*)pathWithQueryParamsToString:(NSString*) path
|
|
||||||
queryParams:(NSDictionary*) queryParams {
|
|
||||||
if(queryParams.count == 0) {
|
|
||||||
return path;
|
|
||||||
}
|
|
||||||
NSString * separator = nil;
|
|
||||||
NSUInteger counter = 0;
|
|
||||||
|
|
||||||
NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path];
|
|
||||||
|
|
||||||
NSDictionary *separatorStyles = @{@"csv" : @",",
|
|
||||||
@"tsv" : @"\t",
|
|
||||||
@"pipes": @"|"
|
|
||||||
};
|
|
||||||
for(NSString * key in [queryParams keyEnumerator]){
|
|
||||||
if (counter == 0) {
|
|
||||||
separator = @"?";
|
|
||||||
} else {
|
|
||||||
separator = @"&";
|
|
||||||
}
|
|
||||||
id queryParam = [queryParams valueForKey:key];
|
|
||||||
if(!queryParam) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
NSString *safeKey = {{classPrefix}}PercentEscapedStringFromString(key);
|
|
||||||
if ([queryParam isKindOfClass:[NSString class]]){
|
|
||||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, {{classPrefix}}PercentEscapedStringFromString(queryParam)]];
|
|
||||||
|
|
||||||
} else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){
|
|
||||||
{{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam;
|
|
||||||
NSArray* values = [coll values];
|
|
||||||
NSString* format = [coll format];
|
|
||||||
|
|
||||||
if([format isEqualToString:@"multi"]) {
|
|
||||||
for(id obj in values) {
|
|
||||||
if (counter > 0) {
|
|
||||||
separator = @"&";
|
|
||||||
}
|
|
||||||
NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]);
|
|
||||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]];
|
|
||||||
counter += 1;
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
NSString * separatorStyle = separatorStyles[format];
|
|
||||||
NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]);
|
|
||||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]];
|
|
||||||
} else {
|
|
||||||
NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]);
|
|
||||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]];
|
|
||||||
}
|
|
||||||
counter += 1;
|
|
||||||
}
|
|
||||||
return requestUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update header and query params based on authentication settings
|
|
||||||
*/
|
|
||||||
- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers
|
|
||||||
queryParams:(NSDictionary *__autoreleasing *)querys
|
|
||||||
WithAuthSettings:(NSArray *)authSettings {
|
|
||||||
|
|
||||||
if (!authSettings || [authSettings count] == 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers];
|
|
||||||
NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys];
|
|
||||||
|
|
||||||
id<{{classPrefix}}Configuration> config = self.configuration;
|
|
||||||
for (NSString *auth in authSettings) {
|
|
||||||
NSDictionary *authSetting = config.authSettings[auth];
|
|
||||||
|
|
||||||
if(!authSetting) { // auth setting is set only if the key is non-empty
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString *type = authSetting[@"in"];
|
|
||||||
NSString *key = authSetting[@"key"];
|
|
||||||
NSString *value = authSetting[@"value"];
|
|
||||||
if ([type isEqualToString:@"header"] && [key length] > 0 ) {
|
|
||||||
headersWithAuth[key] = value;
|
|
||||||
} else if ([type isEqualToString:@"query"] && [key length] != 0) {
|
|
||||||
querysWithAuth[key] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
*headers = [NSDictionary dictionaryWithDictionary:headersWithAuth];
|
|
||||||
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (AFSecurityPolicy *) customSecurityPolicy {
|
|
||||||
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
|
||||||
|
|
||||||
id<{{classPrefix}}Configuration> config = self.configuration;
|
|
||||||
|
|
||||||
if (config.sslCaCert) {
|
|
||||||
NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert];
|
|
||||||
[securityPolicy setPinnedCertificates:@[certData]];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (config.verifySSL) {
|
|
||||||
[securityPolicy setAllowInvalidCertificates:NO];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
[securityPolicy setAllowInvalidCertificates:YES];
|
|
||||||
[securityPolicy setValidatesDomainName:NO];
|
|
||||||
}
|
|
||||||
|
|
||||||
return securityPolicy;
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,147 +0,0 @@
|
|||||||
/**
|
|
||||||
* NOTE: This class is auto generated by the swagger code generator program.
|
|
||||||
* https://github.com/swagger-api/swagger-codegen
|
|
||||||
* Do not edit the class manually.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#import <AFNetworking/AFNetworking.h>
|
|
||||||
#import "{{classPrefix}}Configuration.h"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A key for `NSError` user info dictionaries.
|
|
||||||
*
|
|
||||||
* The corresponding value is the parsed response body for an HTTP error.
|
|
||||||
*/
|
|
||||||
extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
|
|
||||||
|
|
||||||
|
|
||||||
@interface {{classPrefix}}ApiSessionManager : AFHTTPSessionManager
|
|
||||||
|
|
||||||
@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration;
|
|
||||||
|
|
||||||
@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
|
|
||||||
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
|
|
||||||
@property(nonatomic, readonly) NSOperationQueue* queue;
|
|
||||||
|
|
||||||
@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer;
|
|
||||||
|
|
||||||
@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clears Cache
|
|
||||||
*/
|
|
||||||
+(void)clearCache;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Turns on cache
|
|
||||||
*
|
|
||||||
* @param enabled If the cached is enable, must be `YES` or `NO`
|
|
||||||
*/
|
|
||||||
+(void)setCacheEnabled:(BOOL) enabled;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the client unreachable
|
|
||||||
*
|
|
||||||
* @param state off line state, must be `YES` or `NO`
|
|
||||||
*/
|
|
||||||
+(void) setOfflineState:(BOOL) state;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets if the client is unreachable
|
|
||||||
*
|
|
||||||
* @return The client offline state
|
|
||||||
*/
|
|
||||||
+(BOOL) getOfflineState;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the client reachability, this may be overridden by the reachability manager if reachability changes
|
|
||||||
*
|
|
||||||
* @param The client reachability.
|
|
||||||
*/
|
|
||||||
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the client reachability
|
|
||||||
*
|
|
||||||
* @return The client reachability.
|
|
||||||
*/
|
|
||||||
+(AFNetworkReachabilityStatus) getReachabilityStatus;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Customizes the behavior when the reachability changed
|
|
||||||
*
|
|
||||||
* @param changeBlock The block will be executed when the reachability changed.
|
|
||||||
*/
|
|
||||||
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the api client reachability strategy
|
|
||||||
*/
|
|
||||||
- (void)configureCacheReachibility;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets header for request
|
|
||||||
*
|
|
||||||
* @param value The header value
|
|
||||||
* @param forKey The header key
|
|
||||||
*/
|
|
||||||
-(void)setHeaderValue:(NSString*) value
|
|
||||||
forKey:(NSString*) forKey;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates header parameters and query parameters for authentication
|
|
||||||
*
|
|
||||||
* @param headers The header parameter will be udpated, passed by pointer to pointer.
|
|
||||||
* @param querys The query parameters will be updated, passed by pointer to pointer.
|
|
||||||
* @param authSettings The authentication names NSArray.
|
|
||||||
*/
|
|
||||||
- (void) updateHeaderParams:(NSDictionary **)headers
|
|
||||||
queryParams:(NSDictionary **)querys
|
|
||||||
WithAuthSettings:(NSArray *)authSettings;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes the session manager with a configuration.
|
|
||||||
*
|
|
||||||
* @param configuration The configuration implementation
|
|
||||||
*/
|
|
||||||
- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Performs request
|
|
||||||
*
|
|
||||||
* @param path Request url.
|
|
||||||
* @param method Request method.
|
|
||||||
* @param pathParams Request path parameters.
|
|
||||||
* @param queryParams Request query parameters.
|
|
||||||
* @param body Request body.
|
|
||||||
* @param headerParams Request header parameters.
|
|
||||||
* @param authSettings Request authentication names.
|
|
||||||
* @param requestContentType Request content-type.
|
|
||||||
* @param responseContentType Response content-type.
|
|
||||||
* @param completionBlock The block will be executed when the request completed.
|
|
||||||
*
|
|
||||||
* @return The created session task.
|
|
||||||
*/
|
|
||||||
- (NSURLSessionTask *)requestWithCompletionBlock:(NSString*)path
|
|
||||||
method:(NSString*) method
|
|
||||||
pathParams:(NSDictionary *)pathParams
|
|
||||||
queryParams:(NSDictionary*)queryParams
|
|
||||||
formParams:(NSDictionary *)formParams
|
|
||||||
files:(NSDictionary *)files
|
|
||||||
body:(id)body
|
|
||||||
headerParams:(NSDictionary *)headerParams
|
|
||||||
authSettings: (NSArray *)authSettings
|
|
||||||
requestContentType:(NSString *)requestContentType
|
|
||||||
responseContentType:(NSString *)responseContentType
|
|
||||||
responseType:(NSString *)responseType
|
|
||||||
completionBlock:(void (^)(id, NSError *))completionBlock;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Custom security policy
|
|
||||||
*
|
|
||||||
* @return AFSecurityPolicy
|
|
||||||
*/
|
|
||||||
- (AFSecurityPolicy *) customSecurityPolicy;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,14 +0,0 @@
|
|||||||
#import "{{classPrefix}}BasicAuthTokenProvider.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}BasicAuthTokenProvider
|
|
||||||
|
|
||||||
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password {
|
|
||||||
|
|
||||||
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
|
|
||||||
NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding];
|
|
||||||
basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]];
|
|
||||||
|
|
||||||
return basicAuthCredentials;
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,14 +0,0 @@
|
|||||||
/** The `{{classPrefix}}BasicAuthTokenProvider` class creates a basic auth token from username and password.
|
|
||||||
*
|
|
||||||
* NOTE: This class is auto generated by the swagger code generator program.
|
|
||||||
* https://github.com/swagger-api/swagger-codegen
|
|
||||||
* Do not edit the class manually.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#import <Foundation/Foundation.h>
|
|
||||||
|
|
||||||
@interface {{classPrefix}}BasicAuthTokenProvider : NSObject
|
|
||||||
|
|
||||||
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,75 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import "{{classPrefix}}Logger.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@protocol {{classPrefix}}Configuration <NSObject>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api logger
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) {{classPrefix}}Logger *logger;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Base url
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *host;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api key values for Api Key type Authentication
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSDictionary *apiKey;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api key prefix values to be prepend to the respective api key
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSDictionary *apiKeyPrefix;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Username for HTTP Basic Authentication
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *username;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Password for HTTP Basic Authentication
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *password;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Access token for OAuth
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *accessToken;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Temp folder for file download
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *tempFolderPath;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Debug switch, default false
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) BOOL debug;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SSL/TLS verification
|
|
||||||
* Set this to NO to skip verifying SSL certificate when calling API from https server
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) BOOL verifySSL;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SSL/TLS verification
|
|
||||||
* Set this to customize the certificate file to verify the peer
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *sslCaCert;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Authentication Settings
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSDictionary *authSettings;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default headers for all services
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,157 +0,0 @@
|
|||||||
#import "{{classPrefix}}DefaultConfiguration.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}DefaultConfiguration
|
|
||||||
|
|
||||||
#pragma mark - Singleton Methods
|
|
||||||
|
|
||||||
+ (instancetype)sharedConfiguration {
|
|
||||||
|
|
||||||
static {{classPrefix}}DefaultConfiguration *shardConfig = nil;
|
|
||||||
static dispatch_once_t onceToken;
|
|
||||||
dispatch_once(&onceToken, ^{
|
|
||||||
shardConfig = [[self alloc] init];
|
|
||||||
});
|
|
||||||
return shardConfig;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Initialize Methods
|
|
||||||
|
|
||||||
- (instancetype)init {
|
|
||||||
self = [super init];
|
|
||||||
if (self) {
|
|
||||||
_host = @"{{basePath}}";
|
|
||||||
_username = @"";
|
|
||||||
_password = @"";
|
|
||||||
_accessToken= @"";
|
|
||||||
_verifySSL = YES;
|
|
||||||
_mutableApiKey = [NSMutableDictionary dictionary];
|
|
||||||
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
|
|
||||||
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
|
|
||||||
_mutableDefaultHeaders[@"User-Agent"] = {{#httpUserAgent}}@"{{httpUserAgent}}"{{/httpUserAgent}}{{^httpUserAgent}}[NSString stringWithFormat:@"Swagger-Codegen/{{version}}/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]{{/httpUserAgent}};
|
|
||||||
_logger = [{{classPrefix}}Logger sharedLogger];
|
|
||||||
}
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Instance Methods
|
|
||||||
|
|
||||||
- (NSString *) getApiKeyWithPrefix:(NSString *)key {
|
|
||||||
NSString *prefix = self.apiKeyPrefix[key];
|
|
||||||
NSString *apiKey = self.apiKey[key];
|
|
||||||
if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set
|
|
||||||
return [NSString stringWithFormat:@"%@ %@", prefix, apiKey];
|
|
||||||
}
|
|
||||||
else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix
|
|
||||||
return [NSString stringWithFormat:@"%@", self.apiKey[key]];
|
|
||||||
}
|
|
||||||
else { // return empty string if nothing is set
|
|
||||||
return @"";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSString *) getBasicAuthToken {
|
|
||||||
// return empty string if username and password are empty
|
|
||||||
if (self.username.length == 0 && self.password.length == 0){
|
|
||||||
return @"";
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password];
|
|
||||||
NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding];
|
|
||||||
basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]];
|
|
||||||
|
|
||||||
return basicAuthCredentials;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSString *) getAccessToken {
|
|
||||||
if (self.accessToken.length == 0) { // token not set, return empty string
|
|
||||||
return @"";
|
|
||||||
} else {
|
|
||||||
return [NSString stringWithFormat:@"Bearer %@", self.accessToken];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Setter Methods
|
|
||||||
|
|
||||||
- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier {
|
|
||||||
[self.mutableApiKey setValue:apiKey forKey:identifier];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) removeApiKey:(NSString *)identifier {
|
|
||||||
[self.mutableApiKey removeObjectForKey:identifier];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier {
|
|
||||||
[self.mutableApiKeyPrefix setValue:prefix forKey:identifier];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) removeApiKeyPrefix:(NSString *)identifier {
|
|
||||||
[self.mutableApiKeyPrefix removeObjectForKey:identifier];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark -
|
|
||||||
|
|
||||||
- (NSDictionary *) authSettings {
|
|
||||||
return @{
|
|
||||||
{{#authMethods}}
|
|
||||||
{{#isApiKey}}
|
|
||||||
@"{{name}}":
|
|
||||||
@{
|
|
||||||
@"type": @"api_key",
|
|
||||||
@"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}},
|
|
||||||
@"key": @"{{keyParamName}}",
|
|
||||||
@"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"]
|
|
||||||
},
|
|
||||||
{{/isApiKey}}
|
|
||||||
{{#isBasic}}
|
|
||||||
@"{{name}}":
|
|
||||||
@{
|
|
||||||
@"type": @"basic",
|
|
||||||
@"in": @"header",
|
|
||||||
@"key": @"Authorization",
|
|
||||||
@"value": [self getBasicAuthToken]
|
|
||||||
},
|
|
||||||
{{/isBasic}}
|
|
||||||
{{#isOAuth}}
|
|
||||||
@"{{name}}":
|
|
||||||
@{
|
|
||||||
@"type": @"oauth",
|
|
||||||
@"in": @"header",
|
|
||||||
@"key": @"Authorization",
|
|
||||||
@"value": [self getAccessToken]
|
|
||||||
},
|
|
||||||
{{/isOAuth}}
|
|
||||||
{{/authMethods}}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
-(BOOL)debug {
|
|
||||||
return self.logger.isEnabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void)setDebug:(BOOL)debug {
|
|
||||||
self.logger.enabled = debug;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
|
|
||||||
if(!value) {
|
|
||||||
[self.mutableDefaultHeaders removeObjectForKey:key];
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.mutableDefaultHeaders[key] = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void) removeDefaultHeaderForKey:(NSString*)key {
|
|
||||||
[self.mutableDefaultHeaders removeObjectForKey:key];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSString *)defaultHeaderForKey:(NSString *)key {
|
|
||||||
return self.mutableDefaultHeaders[key];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSDictionary *)defaultHeaders {
|
|
||||||
return [self.mutableDefaultHeaders copy];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,134 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import "{{classPrefix}}Configuration.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration>
|
|
||||||
|
|
||||||
+ ({{classPrefix}}DefaultConfiguration *)sharedConfiguration;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default api logger
|
|
||||||
*/
|
|
||||||
@property (nonatomic, strong) {{classPrefix}}Logger * logger;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default api client
|
|
||||||
*/
|
|
||||||
@property (nonatomic) {{classPrefix}}ApiClient *apiClient;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default base url
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *host;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api key values for Api Key type Authentication
|
|
||||||
*
|
|
||||||
* To add or remove api key, use `setApiKey:forApiKeyIdentifier:`.
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic, strong) NSDictionary *apiKey;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api key prefix values to be prepend to the respective api key
|
|
||||||
*
|
|
||||||
* To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`.
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Username for HTTP Basic Authentication
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *username;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Password for HTTP Basic Authentication
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *password;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Access token for OAuth
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *accessToken;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Temp folder for file download
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *tempFolderPath;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Debug switch, default false
|
|
||||||
*/
|
|
||||||
@property (nonatomic) BOOL debug;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SSL/TLS verification
|
|
||||||
* Set this to NO to skip verifying SSL certificate when calling API from https server
|
|
||||||
*/
|
|
||||||
@property (nonatomic) BOOL verifySSL;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SSL/TLS verification
|
|
||||||
* Set this to customize the certificate file to verify the peer
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *sslCaCert;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets API key
|
|
||||||
*
|
|
||||||
* To remove a apiKey for an identifier, just set the apiKey to nil.
|
|
||||||
*
|
|
||||||
* @param apiKey API key or token.
|
|
||||||
* @param identifier API key identifier (authentication schema).
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes api key
|
|
||||||
*
|
|
||||||
* @param identifier API key identifier.
|
|
||||||
*/
|
|
||||||
- (void) removeApiKey:(NSString *)identifier;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the prefix for API key
|
|
||||||
*
|
|
||||||
* @param apiKeyPrefix API key prefix.
|
|
||||||
* @param identifier API key identifier.
|
|
||||||
*/
|
|
||||||
- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes api key prefix
|
|
||||||
*
|
|
||||||
* @param identifier API key identifier.
|
|
||||||
*/
|
|
||||||
- (void) removeApiKeyPrefix:(NSString *)identifier;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default headers for all services
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes header from defaultHeaders
|
|
||||||
*
|
|
||||||
* @param Header name.
|
|
||||||
*/
|
|
||||||
-(void) removeDefaultHeaderForKey:(NSString*)key;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the header for key
|
|
||||||
*
|
|
||||||
* @param value Value for header name
|
|
||||||
* @param key Header name
|
|
||||||
*/
|
|
||||||
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param Header key name.
|
|
||||||
*/
|
|
||||||
-(NSString*) defaultHeaderForKey:(NSString*)key;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,37 +0,0 @@
|
|||||||
#import "{{classPrefix}}JSONRequestSerializer.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}JSONRequestSerializer
|
|
||||||
|
|
||||||
///
|
|
||||||
/// When customize a request serializer,
|
|
||||||
/// the serializer must conform the protocol `AFURLRequestSerialization`
|
|
||||||
/// and implements the protocol method `requestBySerializingRequest:withParameters:error:`
|
|
||||||
///
|
|
||||||
/// @param request The original request.
|
|
||||||
/// @param parameters The parameters to be encoded.
|
|
||||||
/// @param error The error that occurred while attempting to encode the request parameters.
|
|
||||||
///
|
|
||||||
/// @return A serialized request.
|
|
||||||
///
|
|
||||||
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
|
|
||||||
withParameters:(id)parameters
|
|
||||||
error:(NSError *__autoreleasing *)error
|
|
||||||
{
|
|
||||||
if (!parameters) {
|
|
||||||
return request;
|
|
||||||
}
|
|
||||||
// If the body data which will be serialized isn't NSArray or NSDictionary
|
|
||||||
// then put the data in the http request body directly.
|
|
||||||
if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) {
|
|
||||||
return [super requestBySerializingRequest:request withParameters:parameters error:error];
|
|
||||||
}
|
|
||||||
NSMutableURLRequest *mutableRequest = [request mutableCopy];
|
|
||||||
if([parameters isKindOfClass:[NSData class]]) {
|
|
||||||
[mutableRequest setHTTPBody:parameters];
|
|
||||||
} else {
|
|
||||||
[mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]];
|
|
||||||
}
|
|
||||||
return mutableRequest;
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,7 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <AFNetworking/AFURLRequestSerialization.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}JSONRequestSerializer : AFJSONRequestSerializer
|
|
||||||
@end
|
|
@ -1,39 +0,0 @@
|
|||||||
#import "{{classPrefix}}JSONResponseSerializer.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}JSONResponseSerializer
|
|
||||||
|
|
||||||
///
|
|
||||||
/// When customize a response serializer,
|
|
||||||
/// the serializer must conform the protocol `AFURLResponseSerialization`
|
|
||||||
/// and implements the protocol method `responseObjectForResponse:error:`
|
|
||||||
///
|
|
||||||
/// @param response The response to be processed.
|
|
||||||
/// @param data The response data to be decoded.
|
|
||||||
/// @param error The error that occurred while attempting to decode the response data.
|
|
||||||
///
|
|
||||||
/// @return The object decoded from the specified response data.
|
|
||||||
///
|
|
||||||
- (id) responseObjectForResponse:(NSURLResponse *)response
|
|
||||||
data:(NSData *)data
|
|
||||||
error:(NSError *__autoreleasing *)error {
|
|
||||||
NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error];
|
|
||||||
|
|
||||||
// if response data is not a valid json, return string of data.
|
|
||||||
if ([self isParseError:*error]) {
|
|
||||||
*error = nil;
|
|
||||||
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
|
||||||
return responseString;
|
|
||||||
}
|
|
||||||
|
|
||||||
return responseJson;
|
|
||||||
}
|
|
||||||
|
|
||||||
-(BOOL)isParseError:(NSError *)error {
|
|
||||||
return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840;
|
|
||||||
}
|
|
||||||
|
|
||||||
+ (instancetype)serializer {
|
|
||||||
return [self serializerWithReadingOptions:NSJSONReadingAllowFragments];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,8 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <AFNetworking/AFURLResponseSerialization.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer
|
|
||||||
|
|
||||||
@end
|
|
@ -1,8 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <JSONModel/JSONValueTransformer.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface JSONValueTransformer (ISO8601)
|
|
||||||
|
|
||||||
@end
|
|
@ -1,11 +0,0 @@
|
|||||||
#import <ISO8601/NSDate+ISO8601.h>
|
|
||||||
#import "JSONValueTransformer+ISO8601.h"
|
|
||||||
|
|
||||||
@implementation JSONValueTransformer (ISO8601)
|
|
||||||
|
|
||||||
- (NSDate *) NSDateFromNSString:(NSString *)string
|
|
||||||
{
|
|
||||||
return [NSDate dateWithISO8601String:string];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,42 +0,0 @@
|
|||||||
#import "{{classPrefix}}Object.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}Object
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Workaround for JSONModel multithreading issues
|
|
||||||
* https://github.com/icanzilb/JSONModel/issues/441
|
|
||||||
*/
|
|
||||||
- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err {
|
|
||||||
static NSMutableSet *classNames;
|
|
||||||
static dispatch_once_t onceToken;
|
|
||||||
dispatch_once(&onceToken, ^{
|
|
||||||
classNames = [NSMutableSet new];
|
|
||||||
});
|
|
||||||
|
|
||||||
BOOL initSync;
|
|
||||||
@synchronized([self class])
|
|
||||||
{
|
|
||||||
NSString *className = NSStringFromClass([self class]);
|
|
||||||
initSync = ![classNames containsObject:className];
|
|
||||||
if(initSync)
|
|
||||||
{
|
|
||||||
[classNames addObject:className];
|
|
||||||
self = [super initWithDictionary:dict error:err];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if(!initSync)
|
|
||||||
{
|
|
||||||
self = [super initWithDictionary:dict error:err];
|
|
||||||
}
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the string presentation of the object.
|
|
||||||
* This method will be called when logging model object using `NSLog`.
|
|
||||||
*/
|
|
||||||
- (NSString *)description {
|
|
||||||
return [[self toDictionary] description];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,8 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <JSONModel/JSONModel.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}Object : JSONModel
|
|
||||||
|
|
||||||
@end
|
|
@ -1,20 +0,0 @@
|
|||||||
#import "{{classPrefix}}QueryParamCollection.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}QueryParamCollection
|
|
||||||
|
|
||||||
@synthesize values = _values;
|
|
||||||
@synthesize format = _format;
|
|
||||||
|
|
||||||
- (id)initWithValuesAndFormat:(NSArray *)values
|
|
||||||
format:(NSString *)format {
|
|
||||||
|
|
||||||
self = [super init];
|
|
||||||
if (self) {
|
|
||||||
_values = values;
|
|
||||||
_format = format;
|
|
||||||
}
|
|
||||||
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,13 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}QueryParamCollection : NSObject
|
|
||||||
|
|
||||||
@property(nonatomic, readonly) NSArray* values;
|
|
||||||
@property(nonatomic, readonly) NSString* format;
|
|
||||||
|
|
||||||
- (id) initWithValuesAndFormat: (NSArray*) values
|
|
||||||
format: (NSString*) format;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,143 +0,0 @@
|
|||||||
# {{podName}}
|
|
||||||
|
|
||||||
{{#appDescription}}
|
|
||||||
{{{appDescription}}}
|
|
||||||
{{/appDescription}}
|
|
||||||
|
|
||||||
This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project:
|
|
||||||
|
|
||||||
- API version: {{appVersion}}
|
|
||||||
- Package version: {{artifactVersion}}
|
|
||||||
- Build date: {{generatedDate}}
|
|
||||||
- Build package: {{generatorClass}}
|
|
||||||
{{#infoUrl}}
|
|
||||||
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
|
|
||||||
{{/infoUrl}}
|
|
||||||
|
|
||||||
## Requirements
|
|
||||||
|
|
||||||
The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.com/questions/7778356/how-to-enable-disable-automatic-reference-counting) to be enabled in the Xcode project.
|
|
||||||
|
|
||||||
## Installation & Usage
|
|
||||||
### Install from Github using [CocoaPods](https://cocoapods.org/)
|
|
||||||
|
|
||||||
Add the following to the Podfile:
|
|
||||||
|
|
||||||
```ruby
|
|
||||||
pod '{{podName}}', :git => 'https://github.com/{{gitUserId}}/{{gitRepoId}}.git'
|
|
||||||
```
|
|
||||||
|
|
||||||
To specify a particular branch, append `, :branch => 'branch-name-here'`
|
|
||||||
|
|
||||||
To specify a particular commit, append `, :commit => '11aa22'`
|
|
||||||
|
|
||||||
### Install from local path using [CocoaPods](https://cocoapods.org/)
|
|
||||||
|
|
||||||
Put the SDK under your project folder (e.g. /path/to/objc_project/Vendor/{{podName}}) and then add the following to the Podfile:
|
|
||||||
|
|
||||||
```ruby
|
|
||||||
pod '{{podName}}', :path => 'Vendor/{{podName}}'
|
|
||||||
```
|
|
||||||
|
|
||||||
### Usage
|
|
||||||
|
|
||||||
Import the following:
|
|
||||||
|
|
||||||
```objc
|
|
||||||
#import <{{podName}}/{{{classPrefix}}}ApiClient.h>
|
|
||||||
#import <{{podName}}/{{{classPrefix}}}Configuration.h>
|
|
||||||
// load models
|
|
||||||
{{#models}}{{#model}}#import <{{podName}}/{{{classname}}}.h>
|
|
||||||
{{/model}}{{/models}}// load API classes for accessing endpoints
|
|
||||||
{{#apiInfo}}{{#apis}}#import <{{podName}}/{{{classname}}}.h>
|
|
||||||
{{/apis}}{{/apiInfo}}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Recommendation
|
|
||||||
|
|
||||||
It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue.
|
|
||||||
|
|
||||||
## Getting Started
|
|
||||||
|
|
||||||
Please follow the [installation procedure](#installation--usage) and then run the following:
|
|
||||||
|
|
||||||
```objc
|
|
||||||
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
|
|
||||||
{{#hasAuthMethods}}
|
|
||||||
{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig];
|
|
||||||
{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}})
|
|
||||||
[apiConfig setUsername:@"YOUR_USERNAME"];
|
|
||||||
[apiConfig setPassword:@"YOUR_PASSWORD"];
|
|
||||||
{{/isBasic}}{{#isApiKey}}
|
|
||||||
// Configure API key authorization: (authentication scheme: {{{name}}})
|
|
||||||
[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"];
|
|
||||||
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
|
|
||||||
//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"];
|
|
||||||
{{/isApiKey}}{{#isOAuth}}
|
|
||||||
// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}})
|
|
||||||
[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
|
|
||||||
{{/isOAuth}}{{/authMethods}}
|
|
||||||
{{/hasAuthMethods}}
|
|
||||||
|
|
||||||
{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
|
|
||||||
{{/allParams}}
|
|
||||||
|
|
||||||
{{classname}} *apiInstance = [[{{classname}} alloc] init];
|
|
||||||
|
|
||||||
{{#summary}}// {{{.}}}
|
|
||||||
{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
|
|
||||||
{{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}}
|
|
||||||
{{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) {
|
|
||||||
{{#returnType}}
|
|
||||||
if (output) {
|
|
||||||
NSLog(@"%@", output);
|
|
||||||
}
|
|
||||||
{{/returnType}}
|
|
||||||
if (error) {
|
|
||||||
NSLog(@"Error: %@", error);
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 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}}
|
|
||||||
|
|
@ -1,161 +0,0 @@
|
|||||||
{{#operations}}
|
|
||||||
#import "{{classname}}.h"
|
|
||||||
#import "{{classPrefix}}QueryParamCollection.h"
|
|
||||||
{{#imports}}#import "{{import}}.h"
|
|
||||||
{{/imports}}
|
|
||||||
{{newline}}
|
|
||||||
|
|
||||||
@interface {{classname}} ()
|
|
||||||
|
|
||||||
@property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@implementation {{classname}}
|
|
||||||
|
|
||||||
NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain";
|
|
||||||
NSInteger k{{classname}}MissingParamErrorCode = 234513;
|
|
||||||
|
|
||||||
@synthesize sessionManager = _sessionManager;
|
|
||||||
|
|
||||||
#pragma mark - Initialize methods
|
|
||||||
|
|
||||||
- (id)initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager {
|
|
||||||
self = [super init];
|
|
||||||
if (self) {
|
|
||||||
_sessionManager = sessionManager;
|
|
||||||
_defaultHeaders = [NSMutableDictionary dictionary];
|
|
||||||
}
|
|
||||||
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark -
|
|
||||||
|
|
||||||
-(NSString*) defaultHeaderForKey:(NSString*)key {
|
|
||||||
return self.defaultHeaders[key];
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
|
|
||||||
[self setDefaultHeaderValue:value forKey:key];
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key {
|
|
||||||
[self.defaultHeaders setValue:value forKey:key];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Api Methods
|
|
||||||
|
|
||||||
{{#operation}}
|
|
||||||
///
|
|
||||||
/// {{{summary}}}
|
|
||||||
/// {{{notes}}}
|
|
||||||
/// {{#allParams}} @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
|
|
||||||
///
|
|
||||||
/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
|
|
||||||
///
|
|
||||||
-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
|
|
||||||
{{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}}
|
|
||||||
{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler {
|
|
||||||
{{#allParams}}
|
|
||||||
{{#required}}
|
|
||||||
// verify the required parameter '{{paramName}}' is set
|
|
||||||
if ({{paramName}} == nil) {
|
|
||||||
NSParameterAssert({{paramName}});
|
|
||||||
if(handler) {
|
|
||||||
NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"{{paramName}}"] };
|
|
||||||
NSError* error = [NSError errorWithDomain:k{{classname}}ErrorDomain code:k{{classname}}MissingParamErrorCode userInfo:userInfo];
|
|
||||||
handler({{#returnType}}nil, {{/returnType}}error);
|
|
||||||
}
|
|
||||||
return nil;
|
|
||||||
}
|
|
||||||
|
|
||||||
{{/required}}
|
|
||||||
{{/allParams}}
|
|
||||||
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"];
|
|
||||||
|
|
||||||
// remove format in URL if needed
|
|
||||||
[resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)];
|
|
||||||
|
|
||||||
NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init];
|
|
||||||
{{#pathParams}}
|
|
||||||
if ({{paramName}} != nil) {
|
|
||||||
pathParams[@"{{baseName}}"] = {{paramName}};
|
|
||||||
}
|
|
||||||
{{/pathParams}}
|
|
||||||
|
|
||||||
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
|
|
||||||
{{#queryParams}}
|
|
||||||
if ({{paramName}} != nil) {
|
|
||||||
{{#collectionFormat}}
|
|
||||||
queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{paramName}} format: @"{{collectionFormat}}"];
|
|
||||||
{{/collectionFormat}}
|
|
||||||
{{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}}
|
|
||||||
}
|
|
||||||
{{/queryParams}}
|
|
||||||
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders];
|
|
||||||
[headerParams addEntriesFromDictionary:self.defaultHeaders];
|
|
||||||
{{#headerParams}}
|
|
||||||
if ({{paramName}} != nil) {
|
|
||||||
headerParams[@"{{baseName}}"] = {{paramName}};
|
|
||||||
}
|
|
||||||
{{/headerParams}}
|
|
||||||
// HTTP header `Accept`
|
|
||||||
NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]];
|
|
||||||
if(acceptHeader.length > 0) {
|
|
||||||
headerParams[@"Accept"] = acceptHeader;
|
|
||||||
}
|
|
||||||
|
|
||||||
// response content type
|
|
||||||
NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @"";
|
|
||||||
|
|
||||||
// request content type
|
|
||||||
NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]];
|
|
||||||
|
|
||||||
// Authentication setting
|
|
||||||
NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}];
|
|
||||||
|
|
||||||
id bodyParam = nil;
|
|
||||||
NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init];
|
|
||||||
NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init];
|
|
||||||
{{#bodyParam}}
|
|
||||||
bodyParam = {{paramName}};
|
|
||||||
{{/bodyParam}}
|
|
||||||
{{^bodyParam}}
|
|
||||||
{{#formParams}}
|
|
||||||
{{#notFile}}
|
|
||||||
if ({{paramName}}) {
|
|
||||||
formParams[@"{{baseName}}"] = {{paramName}};
|
|
||||||
}
|
|
||||||
{{/notFile}}
|
|
||||||
{{#isFile}}
|
|
||||||
localVarFiles[@"{{paramName}}"] = {{paramName}};
|
|
||||||
{{/isFile}}
|
|
||||||
{{/formParams}}
|
|
||||||
{{/bodyParam}}
|
|
||||||
|
|
||||||
return [self.sessionManager requestWithPath: resourcePath
|
|
||||||
method: @"{{httpMethod}}"
|
|
||||||
pathParams: pathParams
|
|
||||||
queryParams: queryParams
|
|
||||||
formParams: formParams
|
|
||||||
files: localVarFiles
|
|
||||||
body: bodyParam
|
|
||||||
headerParams: headerParams
|
|
||||||
authSettings: authSettings
|
|
||||||
requestContentType: requestContentType
|
|
||||||
responseContentType: responseContentType
|
|
||||||
responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}}
|
|
||||||
completionBlock: ^(id data, NSError *error) {
|
|
||||||
if(handler) {
|
|
||||||
handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
{{/operation}}
|
|
||||||
|
|
||||||
{{newline}}
|
|
||||||
{{/operations}}
|
|
||||||
@end
|
|
@ -1,34 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
{{#imports}}#import "{{import}}.h"
|
|
||||||
{{/imports}}
|
|
||||||
#import "{{classPrefix}}ApiSessionManager.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
|
|
||||||
@interface {{classname}}: NSObject <{{classPrefix}}Api>
|
|
||||||
|
|
||||||
extern NSString* k{{classname}}ErrorDomain;
|
|
||||||
extern NSInteger k{{classname}}MissingParamErrorCode;
|
|
||||||
|
|
||||||
+(instancetype) sharedAPI;
|
|
||||||
|
|
||||||
{{#operations}}
|
|
||||||
{{#operation}}
|
|
||||||
/// {{{summary}}}
|
|
||||||
/// {{#notes}}{{{notes}}}{{/notes}}
|
|
||||||
///
|
|
||||||
/// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
|
|
||||||
/// {{/allParams}}{{#responses}}
|
|
||||||
/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}}
|
|
||||||
///
|
|
||||||
/// @return {{{returnType}}}
|
|
||||||
-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
|
|
||||||
{{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}}
|
|
||||||
{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler;
|
|
||||||
|
|
||||||
{{newline}}
|
|
||||||
{{/operation}}
|
|
||||||
{{/operations}}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,59 +0,0 @@
|
|||||||
{{#models}}
|
|
||||||
{{#model}}
|
|
||||||
#import "{{classname}}.h"
|
|
||||||
|
|
||||||
@implementation {{classname}}
|
|
||||||
|
|
||||||
- (instancetype)init {
|
|
||||||
self = [super init];
|
|
||||||
if (self) {
|
|
||||||
// initialize property's default value, if any
|
|
||||||
{{#vars}}{{#defaultValue}}self.{{name}} = {{{defaultValue}}};
|
|
||||||
{{/defaultValue}}{{/vars}}
|
|
||||||
}
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
{{#vars}}{{^vendorExtensions.x-unique-id-key}}{{/vendorExtensions.x-unique-id-key}}{{#vendorExtensions.x-unique-id-key}}
|
|
||||||
-(NSString*)indexPropertyName {
|
|
||||||
return @"{{name}}";
|
|
||||||
}
|
|
||||||
{{/vendorExtensions.x-unique-id-key}}{{/vars}}
|
|
||||||
{{#discriminator}}
|
|
||||||
/**
|
|
||||||
* Maps "discriminator" value to the sub-class name, so that inheritance is supported.
|
|
||||||
*/
|
|
||||||
- (id)initWithDictionary:(NSDictionary *)dict error:(NSError *__autoreleasing *)err {
|
|
||||||
NSString * discriminatedClassName = [dict valueForKey:@"{{discriminator}}"];
|
|
||||||
if(discriminatedClassName == nil ){
|
|
||||||
return [super initWithDictionary:dict error:err];
|
|
||||||
}
|
|
||||||
Class class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:discriminatedClassName]);
|
|
||||||
if([self class ] == class) {
|
|
||||||
return [super initWithDictionary:dict error:err];
|
|
||||||
}
|
|
||||||
return [[class alloc] initWithDictionary:dict error: err];
|
|
||||||
}
|
|
||||||
{{/discriminator}}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Maps json key to property name.
|
|
||||||
* This method is used by `JSONModel`.
|
|
||||||
*/
|
|
||||||
+ (JSONKeyMapper *)keyMapper {
|
|
||||||
return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Indicates whether the property with the given name is optional.
|
|
||||||
* If `propertyName` is optional, then return `YES`, otherwise return `NO`.
|
|
||||||
* This method is used by `JSONModel`.
|
|
||||||
*/
|
|
||||||
+ (BOOL)propertyIsOptional:(NSString *)propertyName {
|
|
||||||
|
|
||||||
NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}];
|
|
||||||
return [optionalProperties containsObject:propertyName];
|
|
||||||
}
|
|
||||||
|
|
||||||
{{/model}}
|
|
||||||
@end
|
|
||||||
{{/models}}
|
|
@ -1,25 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import "{{classPrefix}}Object.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
{{#imports}}#import "{{import}}.h"
|
|
||||||
{{/imports}}
|
|
||||||
{{newline}}
|
|
||||||
{{#models}}
|
|
||||||
{{#model}}
|
|
||||||
|
|
||||||
@protocol {{classname}}
|
|
||||||
@end
|
|
||||||
|
|
||||||
@interface {{classname}} : {{#parent}}{{{parent}}}{{/parent}}{{^parent}}{{classPrefix}}Object{{/parent}}
|
|
||||||
|
|
||||||
{{#vars}}
|
|
||||||
{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}}
|
|
||||||
*/{{/description}}
|
|
||||||
@property(nonatomic) {{{ datatype }}} {{name}};
|
|
||||||
{{/vars}}
|
|
||||||
|
|
||||||
@end
|
|
||||||
{{/model}}
|
|
||||||
{{/models}}
|
|
@ -1,37 +0,0 @@
|
|||||||
#
|
|
||||||
# Be sure to run `pod lib lint {{podName}}.podspec' to ensure this is a
|
|
||||||
# valid spec and remove all comments before submitting the spec.
|
|
||||||
#
|
|
||||||
# Any lines starting with a # are optional, but encouraged
|
|
||||||
#
|
|
||||||
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
|
|
||||||
#
|
|
||||||
|
|
||||||
Pod::Spec.new do |s|
|
|
||||||
s.name = "{{podName}}"
|
|
||||||
s.version = "{{podVersion}}"
|
|
||||||
{{#apiInfo}}{{#apis}}{{^hasMore}}
|
|
||||||
s.summary = "{{appName}}"
|
|
||||||
s.description = <<-DESC
|
|
||||||
{{{appDescription}}}
|
|
||||||
DESC
|
|
||||||
{{/hasMore}}{{/apis}}{{/apiInfo}}
|
|
||||||
s.platform = :ios, '7.0'
|
|
||||||
s.requires_arc = true
|
|
||||||
|
|
||||||
{{^useCoreData}}s.framework = 'SystemConfiguration'{{/useCoreData}}{{#useCoreData}}s.frameworks = 'SystemConfiguration', 'CoreData'{{/useCoreData}}
|
|
||||||
|
|
||||||
s.homepage = "{{gitRepoURL}}"
|
|
||||||
s.license = "{{#license}}{{license}}{{/license}}{{^license}}Apache License, Version 2.0{{/license}}"
|
|
||||||
s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" }
|
|
||||||
s.author = { "{{authorName}}" => "{{authorEmail}}" }
|
|
||||||
|
|
||||||
s.source_files = '{{podName}}/**/*.{m,h}'
|
|
||||||
s.public_header_files = '{{podName}}/**/*.h'
|
|
||||||
{{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}}
|
|
||||||
|
|
||||||
s.dependency 'AFNetworking', '~> 3'
|
|
||||||
s.dependency 'JSONModel', '~> 1.2'
|
|
||||||
s.dependency 'ISO8601', '~> 0.5'
|
|
||||||
end
|
|
||||||
|
|
@ -1,74 +0,0 @@
|
|||||||
# Swagger Codegen for the ObjcSessionManager library
|
|
||||||
|
|
||||||
## Overview
|
|
||||||
This is a boiler-plate project to generate your own client library with Swagger. It's goal is
|
|
||||||
to get you started with the basic plumbing so you can put in your own logic. It won't work without
|
|
||||||
your changes applied.
|
|
||||||
|
|
||||||
## What's Swagger?
|
|
||||||
The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service.
|
|
||||||
|
|
||||||
|
|
||||||
Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more.
|
|
||||||
|
|
||||||
## How do I use this?
|
|
||||||
At this point, you've likely generated a client setup. It will include something along these lines:
|
|
||||||
|
|
||||||
```
|
|
||||||
.
|
|
||||||
|- README.md // this file
|
|
||||||
|- pom.xml // build script
|
|
||||||
|-- src
|
|
||||||
|--- main
|
|
||||||
|---- java
|
|
||||||
|----- io.swagger.codegen.languages.ObjcsessionmanagerGenerator.java // generator file
|
|
||||||
|---- resources
|
|
||||||
|----- ObjcSessionManager // template files
|
|
||||||
|----- META-INF
|
|
||||||
|------ services
|
|
||||||
|------- io.swagger.codegen.CodegenConfig
|
|
||||||
```
|
|
||||||
|
|
||||||
You _will_ need to make changes in at least the following:
|
|
||||||
|
|
||||||
`ObjcsessionmanagerGenerator.java`
|
|
||||||
|
|
||||||
Templates in this folder:
|
|
||||||
|
|
||||||
`src/main/resources/ObjcSessionManager`
|
|
||||||
|
|
||||||
Once modified, you can run this:
|
|
||||||
|
|
||||||
```
|
|
||||||
mvn package
|
|
||||||
```
|
|
||||||
|
|
||||||
In your generator project. A single jar file will be produced in `target`. You can now use that with codegen:
|
|
||||||
|
|
||||||
```
|
|
||||||
java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManager -o ./test
|
|
||||||
```
|
|
||||||
|
|
||||||
Now your templates are available to the client generator and you can write output values
|
|
||||||
|
|
||||||
## But how do I modify this?
|
|
||||||
The `ObjcsessionmanagerGenerator.java` has comments in it--lots of comments. There is no good substitute
|
|
||||||
for reading the code more, though. See how the `ObjcsessionmanagerGenerator` implements `CodegenConfig`.
|
|
||||||
That class has the signature of all values that can be overridden.
|
|
||||||
|
|
||||||
For the templates themselves, you have a number of values available to you for generation.
|
|
||||||
You can execute the `java` command from above while passing different debug flags to show
|
|
||||||
the object you have available during client generation:
|
|
||||||
|
|
||||||
```
|
|
||||||
# The following additional debug options are available for all codegen targets:
|
|
||||||
# -DdebugSwagger prints the OpenAPI Specification as interpreted by the codegen
|
|
||||||
# -DdebugModels prints models passed to the template engine
|
|
||||||
# -DdebugOperations prints operations passed to the template engine
|
|
||||||
# -DdebugSupportingFiles prints additional data passed to the template engine
|
|
||||||
|
|
||||||
java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManager -o ./test
|
|
||||||
```
|
|
||||||
|
|
||||||
Will, for example, output the debug info for operations. You can use this info
|
|
||||||
in the `api.mustache` file.
|
|
@ -1,102 +0,0 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>io.swagger</groupId>
|
|
||||||
<artifactId>ObjcSessionManager-swagger-codegen</artifactId>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
<name>ObjcSessionManager-swagger-codegen</name>
|
|
||||||
<version>1.0.0</version>
|
|
||||||
<prerequisites>
|
|
||||||
<maven>2.2.0</maven>
|
|
||||||
</prerequisites>
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>2.12</version>
|
|
||||||
<configuration>
|
|
||||||
<systemProperties>
|
|
||||||
<property>
|
|
||||||
<name>loggerPath</name>
|
|
||||||
<value>conf/log4j.properties</value>
|
|
||||||
</property>
|
|
||||||
</systemProperties>
|
|
||||||
<argLine>-Xms512m -Xmx1500m</argLine>
|
|
||||||
<parallel>methods</parallel>
|
|
||||||
<forkMode>pertest</forkMode>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
|
|
||||||
<!-- attach test jar -->
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-jar-plugin</artifactId>
|
|
||||||
<version>2.2</version>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<goals>
|
|
||||||
<goal>jar</goal>
|
|
||||||
<goal>test-jar</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
<configuration>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.codehaus.mojo</groupId>
|
|
||||||
<artifactId>build-helper-maven-plugin</artifactId>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>add_sources</id>
|
|
||||||
<phase>generate-sources</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>add-source</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<sources>
|
|
||||||
<source>src/main/java</source>
|
|
||||||
</sources>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
<execution>
|
|
||||||
<id>add_test_sources</id>
|
|
||||||
<phase>generate-test-sources</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>add-test-source</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<sources>
|
|
||||||
<source>src/test/java</source>
|
|
||||||
</sources>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<version>2.3.2</version>
|
|
||||||
<configuration>
|
|
||||||
<source>1.6</source>
|
|
||||||
<target>1.6</target>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>io.swagger</groupId>
|
|
||||||
<artifactId>swagger-codegen</artifactId>
|
|
||||||
<version>${swagger-codegen-version}</version>
|
|
||||||
<scope>provided</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
<properties>
|
|
||||||
<swagger-codegen-version>2.1.5</swagger-codegen-version>
|
|
||||||
<maven-plugin-version>1.0.0</maven-plugin-version>
|
|
||||||
<junit-version>4.8.1</junit-version>
|
|
||||||
</properties>
|
|
||||||
</project>
|
|
@ -1,750 +0,0 @@
|
|||||||
package io.swagger.codegen.languages;
|
|
||||||
|
|
||||||
import io.swagger.codegen.*;
|
|
||||||
import io.swagger.models.ArrayModel;
|
|
||||||
import io.swagger.models.Model;
|
|
||||||
import io.swagger.models.properties.*;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
public class ObjcSessionManagerClientCodegen extends DefaultCodegen implements CodegenConfig {
|
|
||||||
public static final String CLASS_PREFIX = "classPrefix";
|
|
||||||
public static final String POD_NAME = "podName";
|
|
||||||
public static final String AUTHOR_NAME = "authorName";
|
|
||||||
public static final String AUTHOR_EMAIL = "authorEmail";
|
|
||||||
public static final String LICENSE = "license";
|
|
||||||
public static final String GIT_REPO_URL = "gitRepoURL";
|
|
||||||
public static final String DEFAULT_LICENSE = "Apache License, Version 2.0";
|
|
||||||
public static final String CORE_DATA = "coreData";
|
|
||||||
|
|
||||||
protected Set<String> foundationClasses = new HashSet<String>();
|
|
||||||
protected String podName = "SwaggerClient";
|
|
||||||
protected String podVersion = "1.0.0";
|
|
||||||
protected String classPrefix = "SWG";
|
|
||||||
protected String authorName = "Swagger";
|
|
||||||
protected String authorEmail = "apiteam@swagger.io";
|
|
||||||
protected String license = DEFAULT_LICENSE;
|
|
||||||
protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen";
|
|
||||||
protected String[] specialWords = {"new", "copy"};
|
|
||||||
protected String apiDocPath = "docs/";
|
|
||||||
protected String modelDocPath = "docs/";
|
|
||||||
protected String modelFilesPath = "Model/";
|
|
||||||
protected String coreFilesPath = "Core/";
|
|
||||||
protected String apiFilesPath = "Api/";
|
|
||||||
|
|
||||||
protected boolean generateCoreData = false;
|
|
||||||
|
|
||||||
protected Set<String> advancedMapingTypes = new HashSet<String>();
|
|
||||||
|
|
||||||
public ObjcSessionManagerClientCodegen() {
|
|
||||||
super();
|
|
||||||
|
|
||||||
outputFolder = "generated-code" + File.separator + "objcSessionManager";
|
|
||||||
modelTemplateFiles.put("model-header.mustache", ".h");
|
|
||||||
modelTemplateFiles.put("model-body.mustache", ".m");
|
|
||||||
apiTemplateFiles.put("api-header.mustache", ".h");
|
|
||||||
apiTemplateFiles.put("api-body.mustache", ".m");
|
|
||||||
embeddedTemplateDir = templateDir = "objcSessionManager";
|
|
||||||
modelDocTemplateFiles.put("model_doc.mustache", ".md");
|
|
||||||
apiDocTemplateFiles.put("api_doc.mustache", ".md");
|
|
||||||
|
|
||||||
defaultIncludes.clear();
|
|
||||||
defaultIncludes.add("bool");
|
|
||||||
defaultIncludes.add("BOOL");
|
|
||||||
defaultIncludes.add("int");
|
|
||||||
defaultIncludes.add("NSURL");
|
|
||||||
defaultIncludes.add("NSString");
|
|
||||||
defaultIncludes.add("NSObject");
|
|
||||||
defaultIncludes.add("NSArray");
|
|
||||||
defaultIncludes.add("NSNumber");
|
|
||||||
defaultIncludes.add("NSDate");
|
|
||||||
defaultIncludes.add("NSDictionary");
|
|
||||||
defaultIncludes.add("NSMutableArray");
|
|
||||||
defaultIncludes.add("NSMutableDictionary");
|
|
||||||
defaultIncludes.add("NSManagedObject");
|
|
||||||
defaultIncludes.add("NSData");
|
|
||||||
|
|
||||||
advancedMapingTypes.add("NSDictionary");
|
|
||||||
advancedMapingTypes.add("NSArray");
|
|
||||||
advancedMapingTypes.add("NSMutableArray");
|
|
||||||
advancedMapingTypes.add("NSMutableDictionary");
|
|
||||||
advancedMapingTypes.add("NSObject");
|
|
||||||
advancedMapingTypes.add("NSNumber");
|
|
||||||
advancedMapingTypes.add("NSURL");
|
|
||||||
advancedMapingTypes.add("NSString");
|
|
||||||
advancedMapingTypes.add("NSDate");
|
|
||||||
|
|
||||||
languageSpecificPrimitives.clear();
|
|
||||||
languageSpecificPrimitives.add("NSNumber");
|
|
||||||
languageSpecificPrimitives.add("NSString");
|
|
||||||
languageSpecificPrimitives.add("NSObject");
|
|
||||||
languageSpecificPrimitives.add("NSDate");
|
|
||||||
languageSpecificPrimitives.add("NSData");
|
|
||||||
languageSpecificPrimitives.add("NSURL");
|
|
||||||
languageSpecificPrimitives.add("bool");
|
|
||||||
languageSpecificPrimitives.add("BOOL");
|
|
||||||
|
|
||||||
typeMapping.clear();
|
|
||||||
typeMapping.put("enum", "NSString");
|
|
||||||
typeMapping.put("date", "NSDate");
|
|
||||||
typeMapping.put("datetime", "NSDate");
|
|
||||||
typeMapping.put("boolean", "NSNumber");
|
|
||||||
typeMapping.put("string", "NSString");
|
|
||||||
typeMapping.put("integer", "NSNumber");
|
|
||||||
typeMapping.put("int", "NSNumber");
|
|
||||||
typeMapping.put("float", "NSNumber");
|
|
||||||
typeMapping.put("long", "NSNumber");
|
|
||||||
typeMapping.put("double", "NSNumber");
|
|
||||||
typeMapping.put("array", "NSArray");
|
|
||||||
typeMapping.put("map", "NSDictionary");
|
|
||||||
typeMapping.put("number", "NSNumber");
|
|
||||||
typeMapping.put("bigdecimal", "NSNumber");
|
|
||||||
typeMapping.put("List", "NSArray");
|
|
||||||
typeMapping.put("object", "NSObject");
|
|
||||||
typeMapping.put("file", "NSURL");
|
|
||||||
typeMapping.put("binary", "NSData");
|
|
||||||
typeMapping.put("bytearray", "NSData");
|
|
||||||
typeMapping.put("byte", "NSData");
|
|
||||||
typeMapping.put("uuid", "NSString");
|
|
||||||
typeMapping.put("password", "NSString");
|
|
||||||
|
|
||||||
// ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm
|
|
||||||
setReservedWordsLowerCase(
|
|
||||||
Arrays.asList(
|
|
||||||
// local variable names in API methods (endpoints)
|
|
||||||
"resourcePath", "pathParams", "queryParams", "headerParams",
|
|
||||||
"responseContentType", "requestContentType", "authSettings",
|
|
||||||
"formParams", "localVarFiles", "bodyParam",
|
|
||||||
// objc reserved words
|
|
||||||
"auto", "else", "long", "switch",
|
|
||||||
"break", "enum", "register", "typedef",
|
|
||||||
"case", "extern", "return", "union",
|
|
||||||
"char", "float", "short", "unsigned",
|
|
||||||
"const", "for", "signed", "void",
|
|
||||||
"continue", "goto", "sizeof", "volatile",
|
|
||||||
"default", "if", "id", "static", "while",
|
|
||||||
"do", "int", "struct", "_Packed",
|
|
||||||
"double", "protocol", "interface", "implementation",
|
|
||||||
"NSObject", "NSInteger", "NSNumber", "CGFloat",
|
|
||||||
"property", "nonatomic", "retain", "strong",
|
|
||||||
"weak", "unsafe_unretained", "readwrite", "readonly",
|
|
||||||
"description"
|
|
||||||
));
|
|
||||||
|
|
||||||
importMapping = new HashMap<String, String>();
|
|
||||||
|
|
||||||
foundationClasses = new HashSet<String>(
|
|
||||||
Arrays.asList(
|
|
||||||
"NSNumber",
|
|
||||||
"NSObject",
|
|
||||||
"NSString",
|
|
||||||
"NSDate",
|
|
||||||
"NSData",
|
|
||||||
"NSURL",
|
|
||||||
"NSDictionary")
|
|
||||||
);
|
|
||||||
|
|
||||||
instantiationTypes.put("array", "NSMutableArray");
|
|
||||||
instantiationTypes.put("map", "NSMutableDictionary");
|
|
||||||
|
|
||||||
cliOptions.clear();
|
|
||||||
cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models").defaultValue("false"));
|
|
||||||
cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`")
|
|
||||||
.defaultValue("SWG"));
|
|
||||||
cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).")
|
|
||||||
.defaultValue("SwaggerClient"));
|
|
||||||
cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version.")
|
|
||||||
.defaultValue("1.0.0"));
|
|
||||||
cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.").defaultValue("Swagger"));
|
|
||||||
cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io"));
|
|
||||||
cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.")
|
|
||||||
.defaultValue("https://github.com/swagger-api/swagger-codegen"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CodegenType getTag() {
|
|
||||||
return CodegenType.CLIENT;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getName() {
|
|
||||||
return "objc";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getHelp() {
|
|
||||||
return "Generates an Objective-C client library.";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void processOpts() {
|
|
||||||
super.processOpts();
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(POD_NAME)) {
|
|
||||||
setPodName((String) additionalProperties.get(POD_NAME));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(CodegenConstants.POD_VERSION)) {
|
|
||||||
setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(CORE_DATA)) {
|
|
||||||
Object coreData = additionalProperties.get(CORE_DATA);
|
|
||||||
if(((String)coreData).equalsIgnoreCase("true")) {
|
|
||||||
generateCoreData = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (additionalProperties.containsKey(CLASS_PREFIX)) {
|
|
||||||
setClassPrefix((String) additionalProperties.get(CLASS_PREFIX));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(AUTHOR_NAME)) {
|
|
||||||
setAuthorName((String) additionalProperties.get(AUTHOR_NAME));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(AUTHOR_EMAIL)) {
|
|
||||||
setAuthorEmail((String) additionalProperties.get(AUTHOR_EMAIL));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (additionalProperties.containsKey(GIT_REPO_URL)) {
|
|
||||||
setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL));
|
|
||||||
}
|
|
||||||
|
|
||||||
if(generateCoreData) {
|
|
||||||
modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h");
|
|
||||||
modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m");
|
|
||||||
modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h");
|
|
||||||
modelTemplateFiles.put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m");
|
|
||||||
}
|
|
||||||
|
|
||||||
additionalProperties.put(POD_NAME, podName);
|
|
||||||
additionalProperties.put(CodegenConstants.POD_VERSION, podVersion);
|
|
||||||
additionalProperties.put(CLASS_PREFIX, classPrefix);
|
|
||||||
additionalProperties.put(AUTHOR_NAME, authorName);
|
|
||||||
additionalProperties.put(AUTHOR_EMAIL, authorEmail);
|
|
||||||
additionalProperties.put(GIT_REPO_URL, gitRepoURL);
|
|
||||||
additionalProperties.put(LICENSE, license);
|
|
||||||
|
|
||||||
// make api and model doc path available in mustache template
|
|
||||||
additionalProperties.put("apiDocPath", apiDocPath);
|
|
||||||
additionalProperties.put("modelDocPath", modelDocPath);
|
|
||||||
additionalProperties.put("useCoreData", generateCoreData);
|
|
||||||
|
|
||||||
modelPackage = podName;
|
|
||||||
apiPackage = podName;
|
|
||||||
|
|
||||||
supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m"));
|
|
||||||
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h"));
|
|
||||||
supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec"));
|
|
||||||
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
|
|
||||||
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); // !!
|
|
||||||
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); // !!
|
|
||||||
|
|
||||||
if(generateCoreData) {
|
|
||||||
supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion"));
|
|
||||||
supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// is apiclient
|
|
||||||
//supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", swaggerFolder, classPrefix + "ApiSessionManager.h"));
|
|
||||||
//supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", swaggerFolder, classPrefix + "ApiSessionManager.m"));
|
|
||||||
|
|
||||||
// protocol!
|
|
||||||
//supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", swaggerFolder, classPrefix + "Configuration.h"));
|
|
||||||
//supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.m"));
|
|
||||||
//supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.h"));
|
|
||||||
|
|
||||||
// missing!
|
|
||||||
//supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.h"));
|
|
||||||
//supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.m"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toInstantiationType(Property p) {
|
|
||||||
if (p instanceof MapProperty) {
|
|
||||||
return instantiationTypes.get("map");
|
|
||||||
} else if (p instanceof ArrayProperty) {
|
|
||||||
return instantiationTypes.get("array");
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getTypeDeclaration(String name) {
|
|
||||||
if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) {
|
|
||||||
return name;
|
|
||||||
} else {
|
|
||||||
return name + "*";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getSwaggerType(Property p) {
|
|
||||||
String swaggerType = super.getSwaggerType(p);
|
|
||||||
String type = null;
|
|
||||||
if (typeMapping.containsKey(swaggerType.toLowerCase())) {
|
|
||||||
type = typeMapping.get(swaggerType.toLowerCase());
|
|
||||||
if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) {
|
|
||||||
return toModelNameWithoutReservedWordCheck(type);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
type = swaggerType;
|
|
||||||
}
|
|
||||||
return toModelNameWithoutReservedWordCheck(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getTypeDeclaration(Property p) {
|
|
||||||
if (p instanceof ArrayProperty) {
|
|
||||||
ArrayProperty ap = (ArrayProperty) p;
|
|
||||||
Property inner = ap.getItems();
|
|
||||||
String innerTypeDeclaration = getTypeDeclaration(inner);
|
|
||||||
if (innerTypeDeclaration.endsWith("*")) {
|
|
||||||
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
|
|
||||||
}
|
|
||||||
// In this condition, type of property p is array of primitive,
|
|
||||||
// return container type with pointer, e.g. `NSArray*<NSString*>*'
|
|
||||||
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
|
|
||||||
return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
|
|
||||||
}
|
|
||||||
// In this condition, type of property p is array of model,
|
|
||||||
// return container type combine inner type with pointer, e.g. `NSArray<SWGTag>*'
|
|
||||||
else {
|
|
||||||
for (String sd : advancedMapingTypes) {
|
|
||||||
if(innerTypeDeclaration.startsWith(sd)) {
|
|
||||||
return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
|
|
||||||
}
|
|
||||||
} else if (p instanceof MapProperty) {
|
|
||||||
MapProperty mp = (MapProperty) p;
|
|
||||||
Property inner = mp.getAdditionalProperties();
|
|
||||||
|
|
||||||
String innerTypeDeclaration = getTypeDeclaration(inner);
|
|
||||||
|
|
||||||
if (innerTypeDeclaration.endsWith("*")) {
|
|
||||||
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
|
|
||||||
}
|
|
||||||
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
|
|
||||||
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + "*>*";
|
|
||||||
} else {
|
|
||||||
for (String s : advancedMapingTypes) {
|
|
||||||
if(innerTypeDeclaration.startsWith(s)) {
|
|
||||||
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + "*>*";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + ">*";
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
String swaggerType = getSwaggerType(p);
|
|
||||||
// In this condition, type of p is objective-c primitive type, e.g. `NSSNumber',
|
|
||||||
// return type of p with pointer, e.g. `NSNumber*'
|
|
||||||
if (languageSpecificPrimitives.contains(swaggerType) &&
|
|
||||||
foundationClasses.contains(swaggerType)) {
|
|
||||||
return swaggerType + "*";
|
|
||||||
}
|
|
||||||
// In this condition, type of p is c primitive type, e.g. `bool',
|
|
||||||
// return type of p, e.g. `bool'
|
|
||||||
else if (languageSpecificPrimitives.contains(swaggerType)) {
|
|
||||||
return swaggerType;
|
|
||||||
}
|
|
||||||
// In this condition, type of p is objective-c object type, e.g. `SWGPet',
|
|
||||||
// return type of p with pointer, e.g. `SWGPet*'
|
|
||||||
else {
|
|
||||||
return swaggerType + "*";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isDataTypeBinary(String dataType) {
|
|
||||||
return dataType.toLowerCase().startsWith("nsdata");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toModelName(String type) {
|
|
||||||
// model name cannot use reserved keyword
|
|
||||||
if (reservedWords.contains(type)) {
|
|
||||||
LOGGER.warn(type+ " (reserved word) cannot be used as model name. Renamed to " + ("model_" + type) + " before further processing");
|
|
||||||
type = "model_" + type; // e.g. return => ModelReturn (after camelize)
|
|
||||||
}
|
|
||||||
|
|
||||||
// model name starts with number
|
|
||||||
/* no need for the fix below as objc model starts with prefix (e.g. SWG)
|
|
||||||
if (type.matches("^\\d.*")) {
|
|
||||||
LOGGER.warn(type + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + type));
|
|
||||||
type = "model_" + type; // e.g. 200Response => Model200Response (after camelize)
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
return toModelNameWithoutReservedWordCheck(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Convert input to proper model name according to ObjC style guide
|
|
||||||
* without checking for reserved words
|
|
||||||
*
|
|
||||||
* @param type Model anme
|
|
||||||
* @return model Name in ObjC style guide
|
|
||||||
*/
|
|
||||||
public String toModelNameWithoutReservedWordCheck(String type) {
|
|
||||||
type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
|
|
||||||
|
|
||||||
// language build-in classes
|
|
||||||
if (typeMapping.keySet().contains(type) ||
|
|
||||||
foundationClasses.contains(type) ||
|
|
||||||
importMapping.values().contains(type) ||
|
|
||||||
defaultIncludes.contains(type) ||
|
|
||||||
languageSpecificPrimitives.contains(type)) {
|
|
||||||
return camelize(type);
|
|
||||||
}
|
|
||||||
// custom classes
|
|
||||||
else {
|
|
||||||
if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix
|
|
||||||
type = type + "_" + modelNameSuffix;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!StringUtils.isEmpty(modelNamePrefix)) { // set model prefix
|
|
||||||
type = modelNamePrefix + "_" + type;
|
|
||||||
}
|
|
||||||
|
|
||||||
return classPrefix + camelize(type); // add class prefix
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toModelFilename(String name) {
|
|
||||||
// should be the same as the model name
|
|
||||||
return toModelName(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void setNonArrayMapProperty(CodegenProperty property, String type) {
|
|
||||||
super.setNonArrayMapProperty(property, type);
|
|
||||||
if ("NSDictionary".equals(type)) {
|
|
||||||
property.setter = "initWithDictionary";
|
|
||||||
} else {
|
|
||||||
property.setter = "initWithValues";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toModelImport(String name) {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String apiDocFileFolder() {
|
|
||||||
return (outputFolder + "/" + apiDocPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String modelDocFileFolder() {
|
|
||||||
return (outputFolder + "/" + modelDocPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toModelDocFilename(String name) {
|
|
||||||
return toModelName(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toApiDocFilename(String name) {
|
|
||||||
return toApiName(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String apiFileFolder() {
|
|
||||||
return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String modelFileFolder() {
|
|
||||||
return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String coreFileFolder() {
|
|
||||||
return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toApiName(String name) {
|
|
||||||
return classPrefix + camelize(name) + "Api";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toApiFilename(String name) {
|
|
||||||
return classPrefix + camelize(name) + "Api";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toVarName(String name) {
|
|
||||||
// sanitize name
|
|
||||||
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
|
|
||||||
|
|
||||||
// if it's all upper case, do noting
|
|
||||||
if (name.matches("^[A-Z_]$")) {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
// if name starting with special word, escape with '_'
|
|
||||||
for(int i =0; i < specialWords.length; i++) {
|
|
||||||
if (name.matches("(?i:^" + specialWords[i] + ".*)"))
|
|
||||||
name = escapeSpecialWord(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
// camelize (lower first character) the variable name
|
|
||||||
// e.g. `pet_id` to `petId`
|
|
||||||
name = camelize(name, true);
|
|
||||||
|
|
||||||
// for reserved word or word starting with number, prepend `_`
|
|
||||||
if (isReservedWord(name) || name.matches("^\\d.*")) {
|
|
||||||
name = escapeReservedWord(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toParamName(String name) {
|
|
||||||
// should be the same as variable name
|
|
||||||
return toVarName(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String escapeReservedWord(String name) {
|
|
||||||
return "_" + name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("static-method")
|
|
||||||
public String escapeSpecialWord(String name) {
|
|
||||||
return "var_" + name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toOperationId(String operationId) {
|
|
||||||
// throw exception if method name is empty
|
|
||||||
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)) {
|
|
||||||
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true));
|
|
||||||
operationId = "call_" + operationId;
|
|
||||||
}
|
|
||||||
|
|
||||||
return camelize(sanitizeName(operationId), true);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setClassPrefix(String classPrefix) {
|
|
||||||
this.classPrefix = classPrefix;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPodName(String podName) {
|
|
||||||
this.podName = podName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPodVersion(String podVersion) {
|
|
||||||
this.podVersion = podVersion;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAuthorEmail(String authorEmail) {
|
|
||||||
this.authorEmail = authorEmail;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAuthorName(String authorName) {
|
|
||||||
this.authorName = authorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setGitRepoURL(String gitRepoURL) {
|
|
||||||
this.gitRepoURL = gitRepoURL;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setLicense(String license) {
|
|
||||||
this.license = license;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
|
|
||||||
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
|
|
||||||
if (operations != null) {
|
|
||||||
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
|
|
||||||
for (CodegenOperation operation : ops) {
|
|
||||||
if (!operation.allParams.isEmpty()) {
|
|
||||||
String firstParamName = operation.allParams.get(0).paramName;
|
|
||||||
operation.vendorExtensions.put("firstParamAltName", camelize(firstParamName));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return objs;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void postProcessModelProperty(CodegenModel model, CodegenProperty property){
|
|
||||||
super.postProcessModelProperty(model,property);
|
|
||||||
property.vendorExtensions.put("x-uppercaseName", camelize(property.name));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return the default value of the property
|
|
||||||
*
|
|
||||||
* @param p Swagger property object
|
|
||||||
* @return string presentation of the default value of the property
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public String toDefaultValue(Property p) {
|
|
||||||
if (p instanceof StringProperty) {
|
|
||||||
StringProperty dp = (StringProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@\"" + dp.getDefault().toString() + "\"";
|
|
||||||
}
|
|
||||||
} else if (p instanceof BooleanProperty) {
|
|
||||||
BooleanProperty dp = (BooleanProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
if (dp.getDefault().toString().equalsIgnoreCase("false"))
|
|
||||||
return "@0";
|
|
||||||
else
|
|
||||||
return "@1";
|
|
||||||
}
|
|
||||||
} else if (p instanceof DateProperty) {
|
|
||||||
// TODO
|
|
||||||
} else if (p instanceof DateTimeProperty) {
|
|
||||||
// TODO
|
|
||||||
} else if (p instanceof DoubleProperty) {
|
|
||||||
DoubleProperty dp = (DoubleProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@" + dp.getDefault().toString();
|
|
||||||
}
|
|
||||||
} else if (p instanceof FloatProperty) {
|
|
||||||
FloatProperty dp = (FloatProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@" + dp.getDefault().toString();
|
|
||||||
}
|
|
||||||
} else if (p instanceof IntegerProperty) {
|
|
||||||
IntegerProperty dp = (IntegerProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@" + dp.getDefault().toString();
|
|
||||||
}
|
|
||||||
} else if (p instanceof LongProperty) {
|
|
||||||
LongProperty dp = (LongProperty) p;
|
|
||||||
if (dp.getDefault() != null) {
|
|
||||||
return "@" + dp.getDefault().toString();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setParameterExampleValue(CodegenParameter p) {
|
|
||||||
String example;
|
|
||||||
|
|
||||||
if (p.defaultValue == null) {
|
|
||||||
example = p.example;
|
|
||||||
} else {
|
|
||||||
example = p.defaultValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
String type = p.baseType;
|
|
||||||
if (type == null) {
|
|
||||||
type = p.dataType;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ("NSString*".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = p.paramName + "_example";
|
|
||||||
}
|
|
||||||
example = "@\"" + escapeText(example) + "\"";
|
|
||||||
} else if ("NSNumber*".equals(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "56";
|
|
||||||
}
|
|
||||||
example = "@" + example;
|
|
||||||
/* OBJC uses NSNumber to represent both int, long, double and float
|
|
||||||
} else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "3.4";
|
|
||||||
} */
|
|
||||||
} else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "True";
|
|
||||||
}
|
|
||||||
} else if ("NSURL*".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "/path/to/file";
|
|
||||||
}
|
|
||||||
//[NSURL fileURLWithPath:@"path/to/file"]
|
|
||||||
example = "[NSURL fileURLWithPath:@\"" + escapeText(example) + "\"]";
|
|
||||||
/*} else if ("NSDate".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "2013-10-20";
|
|
||||||
}
|
|
||||||
example = "'" + escapeText(example) + "'";*/
|
|
||||||
} else if ("NSDate*".equalsIgnoreCase(type)) {
|
|
||||||
if (example == null) {
|
|
||||||
example = "2013-10-20T19:20:30+01:00";
|
|
||||||
}
|
|
||||||
example = "@\"" + escapeText(example) + "\"";
|
|
||||||
} else if (!languageSpecificPrimitives.contains(type)) {
|
|
||||||
// type is a model class, e.g. User
|
|
||||||
type = type.replace("*", "");
|
|
||||||
// e.g. [[SWGPet alloc] init
|
|
||||||
example = "[[" + type + " alloc] init]";
|
|
||||||
} else {
|
|
||||||
LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (example == null) {
|
|
||||||
example = "NULL";
|
|
||||||
} else if (Boolean.TRUE.equals(p.isListContainer)) {
|
|
||||||
example = "@[" + example + "]";
|
|
||||||
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
|
|
||||||
example = "@{@\"key\" : " + example + "}";
|
|
||||||
}
|
|
||||||
|
|
||||||
p.example = example;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String escapeQuotationMark(String input) {
|
|
||||||
// remove " to avoid code injection
|
|
||||||
return input.replace("\"", "");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String escapeUnsafeCharacters(String input) {
|
|
||||||
return input.replace("*/", "*_/").replace("/*", "/_*");
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
io.swagger.codegen.languages.ObjcSessionManagerClientCodegen
|
|
@ -1,461 +0,0 @@
|
|||||||
#import <ISO8601/NSDate+ISO8601.h>
|
|
||||||
|
|
||||||
#import "{{classPrefix}}ApiSessionManager.h"
|
|
||||||
#import "{{classPrefix}}JSONRequestSerializer.h"
|
|
||||||
#import "{{classPrefix}}JSONResponseSerializer.h"
|
|
||||||
#import "{{classPrefix}}QueryParamCollection.h"
|
|
||||||
#import "{{classPrefix}}Object.h"
|
|
||||||
#import "{{classPrefix}}DefaultConfiguration.h"
|
|
||||||
|
|
||||||
|
|
||||||
NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject";
|
|
||||||
|
|
||||||
|
|
||||||
static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) {
|
|
||||||
NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response);
|
|
||||||
if(!headers[@"Content-Disposition"]) {
|
|
||||||
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
|
|
||||||
}
|
|
||||||
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
|
|
||||||
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
|
|
||||||
options:NSRegularExpressionCaseInsensitive
|
|
||||||
error:nil];
|
|
||||||
NSString *contentDispositionHeader = headers[@"Content-Disposition"];
|
|
||||||
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
|
|
||||||
options:0
|
|
||||||
range:NSMakeRange(0, [contentDispositionHeader length])];
|
|
||||||
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@interface {{classPrefix}}ApiSessionManager ()
|
|
||||||
|
|
||||||
@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}ApiSessionManager
|
|
||||||
|
|
||||||
- (instancetype)init {
|
|
||||||
|
|
||||||
return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (instancetype)initWithBaseURL:(NSURL *)url {
|
|
||||||
|
|
||||||
return [self initWithBaseURL:url
|
|
||||||
configuration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]];
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration {
|
|
||||||
|
|
||||||
return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (instancetype)initWithBaseURL:(NSURL *)url
|
|
||||||
configuration:(id<{{classPrefix}}Configuration>)configuration {
|
|
||||||
|
|
||||||
self = [super initWithBaseURL:url];
|
|
||||||
if (self) {
|
|
||||||
_configuration = configuration;
|
|
||||||
}
|
|
||||||
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Setter Methods
|
|
||||||
|
|
||||||
+ (void) setOfflineState:(BOOL) state {
|
|
||||||
offlineState = state;
|
|
||||||
}
|
|
||||||
|
|
||||||
+ (void) setCacheEnabled:(BOOL)enabled {
|
|
||||||
cacheEnabled = enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status {
|
|
||||||
reachabilityStatus = status;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey {
|
|
||||||
[self.requestSerializer setValue:value forHTTPHeaderField:forKey];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)setRequestSerializer:(AFHTTPRequestSerializer<AFURLRequestSerialization> *)requestSerializer {
|
|
||||||
[super setRequestSerializer:requestSerializer];
|
|
||||||
requestSerializer.timeoutInterval = self.timeoutInterval;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Cache Methods
|
|
||||||
|
|
||||||
+(void)clearCache {
|
|
||||||
[[NSURLCache sharedURLCache] removeAllCachedResponses];
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize
|
|
||||||
diskSize: (unsigned long) diskSize {
|
|
||||||
NSAssert(memorySize > 0, @"invalid in-memory cache size");
|
|
||||||
NSAssert(diskSize >= 0, @"invalid disk cache size");
|
|
||||||
|
|
||||||
NSURLCache *cache =
|
|
||||||
[[NSURLCache alloc]
|
|
||||||
initWithMemoryCapacity:memorySize
|
|
||||||
diskCapacity:diskSize
|
|
||||||
diskPath:@"swagger_url_cache"];
|
|
||||||
|
|
||||||
[NSURLCache setSharedURLCache:cache];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Reachability Methods
|
|
||||||
|
|
||||||
+(AFNetworkReachabilityStatus) getReachabilityStatus {
|
|
||||||
return reachabilityStatus;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(BOOL) getOfflineState {
|
|
||||||
return offlineState;
|
|
||||||
}
|
|
||||||
|
|
||||||
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock {
|
|
||||||
reachabilityChangeBlock = changeBlock;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) configureCacheReachibility {
|
|
||||||
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
|
|
||||||
reachabilityStatus = status;
|
|
||||||
{{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status));
|
|
||||||
[{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable];
|
|
||||||
|
|
||||||
// call the reachability block, if configured
|
|
||||||
if (reachabilityChangeBlock != nil) {
|
|
||||||
reachabilityChangeBlock(status);
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
|
|
||||||
[self.reachabilityManager startMonitoring];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Task Methods
|
|
||||||
|
|
||||||
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request
|
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
|
||||||
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
|
|
||||||
{{classPrefix}}DebugLogResponse(response, responseObject,request,error);
|
|
||||||
|
|
||||||
if(!error) {
|
|
||||||
completionBlock(responseObject, nil);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
|
|
||||||
if (responseObject) {
|
|
||||||
// Add in the (parsed) response body.
|
|
||||||
userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject;
|
|
||||||
}
|
|
||||||
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
|
||||||
completionBlock(nil, augmentedError);
|
|
||||||
}];
|
|
||||||
|
|
||||||
return task;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSURLSessionDownloadTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request
|
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
|
||||||
id<{{classPrefix}}Configuration> config = self.configuration;
|
|
||||||
|
|
||||||
NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
|
||||||
{{classPrefix}}DebugLogResponse(response, responseObject,request,error);
|
|
||||||
|
|
||||||
if(error) {
|
|
||||||
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
|
|
||||||
if (responseObject) {
|
|
||||||
userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject;
|
|
||||||
}
|
|
||||||
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
|
|
||||||
completionBlock(nil, augmentedError);
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory();
|
|
||||||
NSString *filename = {{classPrefix}}__fileNameForResponse(response);
|
|
||||||
|
|
||||||
NSString *filepath = [directory stringByAppendingPathComponent:filename];
|
|
||||||
NSURL *file = [NSURL fileURLWithPath:filepath];
|
|
||||||
|
|
||||||
[responseObject writeToURL:file atomically:YES];
|
|
||||||
|
|
||||||
completionBlock(file, nil);
|
|
||||||
}];
|
|
||||||
|
|
||||||
return task;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Perform Request Methods
|
|
||||||
|
|
||||||
- (NSURLSessionTask*) requestWithPath: (NSString*) path
|
|
||||||
method: (NSString*) method
|
|
||||||
pathParams: (NSDictionary *) pathParams
|
|
||||||
queryParams: (NSDictionary*) queryParams
|
|
||||||
formParams: (NSDictionary *) formParams
|
|
||||||
files: (NSDictionary *) files
|
|
||||||
body: (id) body
|
|
||||||
headerParams: (NSDictionary*) headerParams
|
|
||||||
authSettings: (NSArray *) authSettings
|
|
||||||
requestContentType: (NSString*) requestContentType
|
|
||||||
responseContentType: (NSString*) responseContentType
|
|
||||||
responseType: (NSString *) responseType
|
|
||||||
completionBlock: (void (^)(id, NSError *))completionBlock {
|
|
||||||
|
|
||||||
// setting request serializer
|
|
||||||
if ([requestContentType isEqualToString:@"application/json"]) {
|
|
||||||
self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else if ([requestContentType isEqualToString:@"multipart/form-data"]) {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
|
||||||
NSAssert(NO, @"Unsupported request type %@", requestContentType);
|
|
||||||
}
|
|
||||||
|
|
||||||
// setting response serializer
|
|
||||||
if ([responseContentType isEqualToString:@"application/json"]) {
|
|
||||||
self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer];
|
|
||||||
} else {
|
|
||||||
self.responseSerializer = [AFHTTPResponseSerializer serializer];
|
|
||||||
}
|
|
||||||
|
|
||||||
// sanitize parameters
|
|
||||||
pathParams = [self.sanitizer sanitizeForSerialization:pathParams];
|
|
||||||
queryParams = [self.sanitizer sanitizeForSerialization:queryParams];
|
|
||||||
headerParams = [self.sanitizer sanitizeForSerialization:headerParams];
|
|
||||||
formParams = [self.sanitizer sanitizeForSerialization:formParams];
|
|
||||||
if(![body isKindOfClass:[NSData class]]) {
|
|
||||||
body = [self.sanitizer sanitizeForSerialization:body];
|
|
||||||
}
|
|
||||||
|
|
||||||
// auth setting
|
|
||||||
[self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings];
|
|
||||||
|
|
||||||
NSMutableString *resourcePath = [NSMutableString stringWithString:path];
|
|
||||||
[pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
|
||||||
NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj];
|
|
||||||
safeString = {{classPrefix}}PercentEscapedStringFromString(safeString);
|
|
||||||
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
|
|
||||||
}];
|
|
||||||
|
|
||||||
NSMutableURLRequest * request = nil;
|
|
||||||
|
|
||||||
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
|
|
||||||
if ([pathWithQueryParams hasPrefix:@"/"]) {
|
|
||||||
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
|
|
||||||
if (files.count > 0) {
|
|
||||||
__weak __typeof(self)weakSelf = self;
|
|
||||||
request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
|
|
||||||
URLString:urlString
|
|
||||||
parameters:nil
|
|
||||||
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
|
|
||||||
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
|
||||||
NSString *objString = [weakSelf.sanitizer parameterToString:obj];
|
|
||||||
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
|
|
||||||
[formData appendPartWithFormData:data name:key];
|
|
||||||
}];
|
|
||||||
[files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
|
||||||
NSURL *filePath = (NSURL *)obj;
|
|
||||||
[formData appendPartWithFileURL:filePath name:key error:nil];
|
|
||||||
}];
|
|
||||||
} error:nil];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if (formParams) {
|
|
||||||
request = [self.requestSerializer requestWithMethod:method
|
|
||||||
URLString:urlString
|
|
||||||
parameters:formParams
|
|
||||||
error:nil];
|
|
||||||
}
|
|
||||||
if (body) {
|
|
||||||
request = [self.requestSerializer requestWithMethod:method
|
|
||||||
URLString:urlString
|
|
||||||
parameters:body
|
|
||||||
error:nil];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// request cache
|
|
||||||
BOOL hasHeaderParams = [headerParams count] > 0;
|
|
||||||
if (offlineState) {
|
|
||||||
{{classPrefix}}DebugLog(@"%@ cache forced", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
|
|
||||||
}
|
|
||||||
else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) {
|
|
||||||
{{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
{{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath);
|
|
||||||
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasHeaderParams){
|
|
||||||
for(NSString * key in [headerParams keyEnumerator]){
|
|
||||||
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
|
|
||||||
|
|
||||||
[self postProcessRequest:request];
|
|
||||||
|
|
||||||
|
|
||||||
NSURLSessionTask *task = nil
|
|
||||||
|
|
||||||
if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) {
|
|
||||||
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
|
||||||
completionBlock(data, error);
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
[self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
|
|
||||||
NSError * serializationError;
|
|
||||||
id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError];
|
|
||||||
if(!response && !error){
|
|
||||||
error = serializationError;
|
|
||||||
}
|
|
||||||
completionBlock(response, error);
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
|
|
||||||
[task resume];
|
|
||||||
|
|
||||||
return task;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Added for easier override to modify request
|
|
||||||
- (void)postProcessRequest:(NSMutableURLRequest *)request {
|
|
||||||
// Always disable cookies!
|
|
||||||
[request setHTTPShouldHandleCookies:NO];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark -
|
|
||||||
|
|
||||||
- (NSString*)pathWithQueryParamsToString:(NSString*) path
|
|
||||||
queryParams:(NSDictionary*) queryParams {
|
|
||||||
if(queryParams.count == 0) {
|
|
||||||
return path;
|
|
||||||
}
|
|
||||||
NSString * separator = nil;
|
|
||||||
NSUInteger counter = 0;
|
|
||||||
|
|
||||||
NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path];
|
|
||||||
|
|
||||||
NSDictionary *separatorStyles = @{@"csv" : @",",
|
|
||||||
@"tsv" : @"\t",
|
|
||||||
@"pipes": @"|"
|
|
||||||
};
|
|
||||||
for(NSString * key in [queryParams keyEnumerator]){
|
|
||||||
if (counter == 0) {
|
|
||||||
separator = @"?";
|
|
||||||
} else {
|
|
||||||
separator = @"&";
|
|
||||||
}
|
|
||||||
id queryParam = [queryParams valueForKey:key];
|
|
||||||
if(!queryParam) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
NSString *safeKey = {{classPrefix}}PercentEscapedStringFromString(key);
|
|
||||||
if ([queryParam isKindOfClass:[NSString class]]){
|
|
||||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, {{classPrefix}}PercentEscapedStringFromString(queryParam)]];
|
|
||||||
|
|
||||||
} else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){
|
|
||||||
{{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam;
|
|
||||||
NSArray* values = [coll values];
|
|
||||||
NSString* format = [coll format];
|
|
||||||
|
|
||||||
if([format isEqualToString:@"multi"]) {
|
|
||||||
for(id obj in values) {
|
|
||||||
if (counter > 0) {
|
|
||||||
separator = @"&";
|
|
||||||
}
|
|
||||||
NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]);
|
|
||||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]];
|
|
||||||
counter += 1;
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
NSString * separatorStyle = separatorStyles[format];
|
|
||||||
NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]);
|
|
||||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]];
|
|
||||||
} else {
|
|
||||||
NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]);
|
|
||||||
[requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]];
|
|
||||||
}
|
|
||||||
counter += 1;
|
|
||||||
}
|
|
||||||
return requestUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update header and query params based on authentication settings
|
|
||||||
*/
|
|
||||||
- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers
|
|
||||||
queryParams:(NSDictionary *__autoreleasing *)querys
|
|
||||||
WithAuthSettings:(NSArray *)authSettings {
|
|
||||||
|
|
||||||
if (!authSettings || [authSettings count] == 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers];
|
|
||||||
NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys];
|
|
||||||
|
|
||||||
id<{{classPrefix}}Configuration> config = self.configuration;
|
|
||||||
for (NSString *auth in authSettings) {
|
|
||||||
NSDictionary *authSetting = config.authSettings[auth];
|
|
||||||
|
|
||||||
if(!authSetting) { // auth setting is set only if the key is non-empty
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString *type = authSetting[@"in"];
|
|
||||||
NSString *key = authSetting[@"key"];
|
|
||||||
NSString *value = authSetting[@"value"];
|
|
||||||
if ([type isEqualToString:@"header"] && [key length] > 0 ) {
|
|
||||||
headersWithAuth[key] = value;
|
|
||||||
} else if ([type isEqualToString:@"query"] && [key length] != 0) {
|
|
||||||
querysWithAuth[key] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
*headers = [NSDictionary dictionaryWithDictionary:headersWithAuth];
|
|
||||||
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (AFSecurityPolicy *) customSecurityPolicy {
|
|
||||||
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
|
|
||||||
|
|
||||||
id<{{classPrefix}}Configuration> config = self.configuration;
|
|
||||||
|
|
||||||
if (config.sslCaCert) {
|
|
||||||
NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert];
|
|
||||||
[securityPolicy setPinnedCertificates:@[certData]];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (config.verifySSL) {
|
|
||||||
[securityPolicy setAllowInvalidCertificates:NO];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
[securityPolicy setAllowInvalidCertificates:YES];
|
|
||||||
[securityPolicy setValidatesDomainName:NO];
|
|
||||||
}
|
|
||||||
|
|
||||||
return securityPolicy;
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,147 +0,0 @@
|
|||||||
/**
|
|
||||||
* NOTE: This class is auto generated by the swagger code generator program.
|
|
||||||
* https://github.com/swagger-api/swagger-codegen
|
|
||||||
* Do not edit the class manually.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#import <AFNetworking/AFNetworking.h>
|
|
||||||
#import "{{classPrefix}}Configuration.h"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A key for `NSError` user info dictionaries.
|
|
||||||
*
|
|
||||||
* The corresponding value is the parsed response body for an HTTP error.
|
|
||||||
*/
|
|
||||||
extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
|
|
||||||
|
|
||||||
|
|
||||||
@interface {{classPrefix}}ApiSessionManager : AFHTTPSessionManager
|
|
||||||
|
|
||||||
@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration;
|
|
||||||
|
|
||||||
@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
|
|
||||||
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
|
|
||||||
@property(nonatomic, readonly) NSOperationQueue* queue;
|
|
||||||
|
|
||||||
@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer;
|
|
||||||
|
|
||||||
@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clears Cache
|
|
||||||
*/
|
|
||||||
+(void)clearCache;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Turns on cache
|
|
||||||
*
|
|
||||||
* @param enabled If the cached is enable, must be `YES` or `NO`
|
|
||||||
*/
|
|
||||||
+(void)setCacheEnabled:(BOOL) enabled;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the client unreachable
|
|
||||||
*
|
|
||||||
* @param state off line state, must be `YES` or `NO`
|
|
||||||
*/
|
|
||||||
+(void) setOfflineState:(BOOL) state;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets if the client is unreachable
|
|
||||||
*
|
|
||||||
* @return The client offline state
|
|
||||||
*/
|
|
||||||
+(BOOL) getOfflineState;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the client reachability, this may be overridden by the reachability manager if reachability changes
|
|
||||||
*
|
|
||||||
* @param The client reachability.
|
|
||||||
*/
|
|
||||||
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the client reachability
|
|
||||||
*
|
|
||||||
* @return The client reachability.
|
|
||||||
*/
|
|
||||||
+(AFNetworkReachabilityStatus) getReachabilityStatus;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Customizes the behavior when the reachability changed
|
|
||||||
*
|
|
||||||
* @param changeBlock The block will be executed when the reachability changed.
|
|
||||||
*/
|
|
||||||
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the api client reachability strategy
|
|
||||||
*/
|
|
||||||
- (void)configureCacheReachibility;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets header for request
|
|
||||||
*
|
|
||||||
* @param value The header value
|
|
||||||
* @param forKey The header key
|
|
||||||
*/
|
|
||||||
-(void)setHeaderValue:(NSString*) value
|
|
||||||
forKey:(NSString*) forKey;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates header parameters and query parameters for authentication
|
|
||||||
*
|
|
||||||
* @param headers The header parameter will be udpated, passed by pointer to pointer.
|
|
||||||
* @param querys The query parameters will be updated, passed by pointer to pointer.
|
|
||||||
* @param authSettings The authentication names NSArray.
|
|
||||||
*/
|
|
||||||
- (void) updateHeaderParams:(NSDictionary **)headers
|
|
||||||
queryParams:(NSDictionary **)querys
|
|
||||||
WithAuthSettings:(NSArray *)authSettings;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes the session manager with a configuration.
|
|
||||||
*
|
|
||||||
* @param configuration The configuration implementation
|
|
||||||
*/
|
|
||||||
- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Performs request
|
|
||||||
*
|
|
||||||
* @param path Request url.
|
|
||||||
* @param method Request method.
|
|
||||||
* @param pathParams Request path parameters.
|
|
||||||
* @param queryParams Request query parameters.
|
|
||||||
* @param body Request body.
|
|
||||||
* @param headerParams Request header parameters.
|
|
||||||
* @param authSettings Request authentication names.
|
|
||||||
* @param requestContentType Request content-type.
|
|
||||||
* @param responseContentType Response content-type.
|
|
||||||
* @param completionBlock The block will be executed when the request completed.
|
|
||||||
*
|
|
||||||
* @return The created session task.
|
|
||||||
*/
|
|
||||||
- (NSURLSessionTask *)requestWithCompletionBlock:(NSString*)path
|
|
||||||
method:(NSString*) method
|
|
||||||
pathParams:(NSDictionary *)pathParams
|
|
||||||
queryParams:(NSDictionary*)queryParams
|
|
||||||
formParams:(NSDictionary *)formParams
|
|
||||||
files:(NSDictionary *)files
|
|
||||||
body:(id)body
|
|
||||||
headerParams:(NSDictionary *)headerParams
|
|
||||||
authSettings: (NSArray *)authSettings
|
|
||||||
requestContentType:(NSString *)requestContentType
|
|
||||||
responseContentType:(NSString *)responseContentType
|
|
||||||
responseType:(NSString *)responseType
|
|
||||||
completionBlock:(void (^)(id, NSError *))completionBlock;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Custom security policy
|
|
||||||
*
|
|
||||||
* @return AFSecurityPolicy
|
|
||||||
*/
|
|
||||||
- (AFSecurityPolicy *) customSecurityPolicy;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,14 +0,0 @@
|
|||||||
#import "{{classPrefix}}BasicAuthTokenProvider.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}BasicAuthTokenProvider
|
|
||||||
|
|
||||||
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password {
|
|
||||||
|
|
||||||
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
|
|
||||||
NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding];
|
|
||||||
basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]];
|
|
||||||
|
|
||||||
return basicAuthCredentials;
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,14 +0,0 @@
|
|||||||
/** The `{{classPrefix}}BasicAuthTokenProvider` class creates a basic auth token from username and password.
|
|
||||||
*
|
|
||||||
* NOTE: This class is auto generated by the swagger code generator program.
|
|
||||||
* https://github.com/swagger-api/swagger-codegen
|
|
||||||
* Do not edit the class manually.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#import <Foundation/Foundation.h>
|
|
||||||
|
|
||||||
@interface {{classPrefix}}BasicAuthTokenProvider : NSObject
|
|
||||||
|
|
||||||
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,75 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import "{{classPrefix}}Logger.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@protocol {{classPrefix}}Configuration <NSObject>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api logger
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) {{classPrefix}}Logger *logger;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Base url
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *host;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api key values for Api Key type Authentication
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSDictionary *apiKey;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api key prefix values to be prepend to the respective api key
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSDictionary *apiKeyPrefix;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Username for HTTP Basic Authentication
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *username;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Password for HTTP Basic Authentication
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *password;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Access token for OAuth
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *accessToken;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Temp folder for file download
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *tempFolderPath;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Debug switch, default false
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) BOOL debug;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SSL/TLS verification
|
|
||||||
* Set this to NO to skip verifying SSL certificate when calling API from https server
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) BOOL verifySSL;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SSL/TLS verification
|
|
||||||
* Set this to customize the certificate file to verify the peer
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSString *sslCaCert;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Authentication Settings
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic) NSDictionary *authSettings;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default headers for all services
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,157 +0,0 @@
|
|||||||
#import "{{classPrefix}}DefaultConfiguration.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}DefaultConfiguration
|
|
||||||
|
|
||||||
#pragma mark - Singleton Methods
|
|
||||||
|
|
||||||
+ (instancetype)sharedConfiguration {
|
|
||||||
|
|
||||||
static {{classPrefix}}DefaultConfiguration *shardConfig = nil;
|
|
||||||
static dispatch_once_t onceToken;
|
|
||||||
dispatch_once(&onceToken, ^{
|
|
||||||
shardConfig = [[self alloc] init];
|
|
||||||
});
|
|
||||||
return shardConfig;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Initialize Methods
|
|
||||||
|
|
||||||
- (instancetype)init {
|
|
||||||
self = [super init];
|
|
||||||
if (self) {
|
|
||||||
_host = @"{{basePath}}";
|
|
||||||
_username = @"";
|
|
||||||
_password = @"";
|
|
||||||
_accessToken= @"";
|
|
||||||
_verifySSL = YES;
|
|
||||||
_mutableApiKey = [NSMutableDictionary dictionary];
|
|
||||||
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
|
|
||||||
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
|
|
||||||
_mutableDefaultHeaders[@"User-Agent"] = {{#httpUserAgent}}@"{{httpUserAgent}}"{{/httpUserAgent}}{{^httpUserAgent}}[NSString stringWithFormat:@"Swagger-Codegen/{{version}}/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]{{/httpUserAgent}};
|
|
||||||
_logger = [{{classPrefix}}Logger sharedLogger];
|
|
||||||
}
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Instance Methods
|
|
||||||
|
|
||||||
- (NSString *) getApiKeyWithPrefix:(NSString *)key {
|
|
||||||
NSString *prefix = self.apiKeyPrefix[key];
|
|
||||||
NSString *apiKey = self.apiKey[key];
|
|
||||||
if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set
|
|
||||||
return [NSString stringWithFormat:@"%@ %@", prefix, apiKey];
|
|
||||||
}
|
|
||||||
else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix
|
|
||||||
return [NSString stringWithFormat:@"%@", self.apiKey[key]];
|
|
||||||
}
|
|
||||||
else { // return empty string if nothing is set
|
|
||||||
return @"";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSString *) getBasicAuthToken {
|
|
||||||
// return empty string if username and password are empty
|
|
||||||
if (self.username.length == 0 && self.password.length == 0){
|
|
||||||
return @"";
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password];
|
|
||||||
NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding];
|
|
||||||
basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]];
|
|
||||||
|
|
||||||
return basicAuthCredentials;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSString *) getAccessToken {
|
|
||||||
if (self.accessToken.length == 0) { // token not set, return empty string
|
|
||||||
return @"";
|
|
||||||
} else {
|
|
||||||
return [NSString stringWithFormat:@"Bearer %@", self.accessToken];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Setter Methods
|
|
||||||
|
|
||||||
- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier {
|
|
||||||
[self.mutableApiKey setValue:apiKey forKey:identifier];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) removeApiKey:(NSString *)identifier {
|
|
||||||
[self.mutableApiKey removeObjectForKey:identifier];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier {
|
|
||||||
[self.mutableApiKeyPrefix setValue:prefix forKey:identifier];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) removeApiKeyPrefix:(NSString *)identifier {
|
|
||||||
[self.mutableApiKeyPrefix removeObjectForKey:identifier];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark -
|
|
||||||
|
|
||||||
- (NSDictionary *) authSettings {
|
|
||||||
return @{
|
|
||||||
{{#authMethods}}
|
|
||||||
{{#isApiKey}}
|
|
||||||
@"{{name}}":
|
|
||||||
@{
|
|
||||||
@"type": @"api_key",
|
|
||||||
@"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}},
|
|
||||||
@"key": @"{{keyParamName}}",
|
|
||||||
@"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"]
|
|
||||||
},
|
|
||||||
{{/isApiKey}}
|
|
||||||
{{#isBasic}}
|
|
||||||
@"{{name}}":
|
|
||||||
@{
|
|
||||||
@"type": @"basic",
|
|
||||||
@"in": @"header",
|
|
||||||
@"key": @"Authorization",
|
|
||||||
@"value": [self getBasicAuthToken]
|
|
||||||
},
|
|
||||||
{{/isBasic}}
|
|
||||||
{{#isOAuth}}
|
|
||||||
@"{{name}}":
|
|
||||||
@{
|
|
||||||
@"type": @"oauth",
|
|
||||||
@"in": @"header",
|
|
||||||
@"key": @"Authorization",
|
|
||||||
@"value": [self getAccessToken]
|
|
||||||
},
|
|
||||||
{{/isOAuth}}
|
|
||||||
{{/authMethods}}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
-(BOOL)debug {
|
|
||||||
return self.logger.isEnabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void)setDebug:(BOOL)debug {
|
|
||||||
self.logger.enabled = debug;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
|
|
||||||
if(!value) {
|
|
||||||
[self.mutableDefaultHeaders removeObjectForKey:key];
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.mutableDefaultHeaders[key] = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void) removeDefaultHeaderForKey:(NSString*)key {
|
|
||||||
[self.mutableDefaultHeaders removeObjectForKey:key];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSString *)defaultHeaderForKey:(NSString *)key {
|
|
||||||
return self.mutableDefaultHeaders[key];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (NSDictionary *)defaultHeaders {
|
|
||||||
return [self.mutableDefaultHeaders copy];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,134 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import "{{classPrefix}}Configuration.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration>
|
|
||||||
|
|
||||||
+ ({{classPrefix}}DefaultConfiguration *)sharedConfiguration;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default api logger
|
|
||||||
*/
|
|
||||||
@property (nonatomic, strong) {{classPrefix}}Logger * logger;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default api client
|
|
||||||
*/
|
|
||||||
@property (nonatomic) {{classPrefix}}ApiClient *apiClient;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default base url
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *host;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api key values for Api Key type Authentication
|
|
||||||
*
|
|
||||||
* To add or remove api key, use `setApiKey:forApiKeyIdentifier:`.
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic, strong) NSDictionary *apiKey;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Api key prefix values to be prepend to the respective api key
|
|
||||||
*
|
|
||||||
* To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`.
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Username for HTTP Basic Authentication
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *username;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Password for HTTP Basic Authentication
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *password;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Access token for OAuth
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *accessToken;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Temp folder for file download
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *tempFolderPath;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Debug switch, default false
|
|
||||||
*/
|
|
||||||
@property (nonatomic) BOOL debug;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SSL/TLS verification
|
|
||||||
* Set this to NO to skip verifying SSL certificate when calling API from https server
|
|
||||||
*/
|
|
||||||
@property (nonatomic) BOOL verifySSL;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SSL/TLS verification
|
|
||||||
* Set this to customize the certificate file to verify the peer
|
|
||||||
*/
|
|
||||||
@property (nonatomic) NSString *sslCaCert;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets API key
|
|
||||||
*
|
|
||||||
* To remove a apiKey for an identifier, just set the apiKey to nil.
|
|
||||||
*
|
|
||||||
* @param apiKey API key or token.
|
|
||||||
* @param identifier API key identifier (authentication schema).
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes api key
|
|
||||||
*
|
|
||||||
* @param identifier API key identifier.
|
|
||||||
*/
|
|
||||||
- (void) removeApiKey:(NSString *)identifier;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the prefix for API key
|
|
||||||
*
|
|
||||||
* @param apiKeyPrefix API key prefix.
|
|
||||||
* @param identifier API key identifier.
|
|
||||||
*/
|
|
||||||
- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes api key prefix
|
|
||||||
*
|
|
||||||
* @param identifier API key identifier.
|
|
||||||
*/
|
|
||||||
- (void) removeApiKeyPrefix:(NSString *)identifier;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Default headers for all services
|
|
||||||
*/
|
|
||||||
@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes header from defaultHeaders
|
|
||||||
*
|
|
||||||
* @param Header name.
|
|
||||||
*/
|
|
||||||
-(void) removeDefaultHeaderForKey:(NSString*)key;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the header for key
|
|
||||||
*
|
|
||||||
* @param value Value for header name
|
|
||||||
* @param key Header name
|
|
||||||
*/
|
|
||||||
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param Header key name.
|
|
||||||
*/
|
|
||||||
-(NSString*) defaultHeaderForKey:(NSString*)key;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,37 +0,0 @@
|
|||||||
#import "{{classPrefix}}JSONRequestSerializer.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}JSONRequestSerializer
|
|
||||||
|
|
||||||
///
|
|
||||||
/// When customize a request serializer,
|
|
||||||
/// the serializer must conform the protocol `AFURLRequestSerialization`
|
|
||||||
/// and implements the protocol method `requestBySerializingRequest:withParameters:error:`
|
|
||||||
///
|
|
||||||
/// @param request The original request.
|
|
||||||
/// @param parameters The parameters to be encoded.
|
|
||||||
/// @param error The error that occurred while attempting to encode the request parameters.
|
|
||||||
///
|
|
||||||
/// @return A serialized request.
|
|
||||||
///
|
|
||||||
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
|
|
||||||
withParameters:(id)parameters
|
|
||||||
error:(NSError *__autoreleasing *)error
|
|
||||||
{
|
|
||||||
if (!parameters) {
|
|
||||||
return request;
|
|
||||||
}
|
|
||||||
// If the body data which will be serialized isn't NSArray or NSDictionary
|
|
||||||
// then put the data in the http request body directly.
|
|
||||||
if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) {
|
|
||||||
return [super requestBySerializingRequest:request withParameters:parameters error:error];
|
|
||||||
}
|
|
||||||
NSMutableURLRequest *mutableRequest = [request mutableCopy];
|
|
||||||
if([parameters isKindOfClass:[NSData class]]) {
|
|
||||||
[mutableRequest setHTTPBody:parameters];
|
|
||||||
} else {
|
|
||||||
[mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]];
|
|
||||||
}
|
|
||||||
return mutableRequest;
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,7 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <AFNetworking/AFURLRequestSerialization.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}JSONRequestSerializer : AFJSONRequestSerializer
|
|
||||||
@end
|
|
@ -1,39 +0,0 @@
|
|||||||
#import "{{classPrefix}}JSONResponseSerializer.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}JSONResponseSerializer
|
|
||||||
|
|
||||||
///
|
|
||||||
/// When customize a response serializer,
|
|
||||||
/// the serializer must conform the protocol `AFURLResponseSerialization`
|
|
||||||
/// and implements the protocol method `responseObjectForResponse:error:`
|
|
||||||
///
|
|
||||||
/// @param response The response to be processed.
|
|
||||||
/// @param data The response data to be decoded.
|
|
||||||
/// @param error The error that occurred while attempting to decode the response data.
|
|
||||||
///
|
|
||||||
/// @return The object decoded from the specified response data.
|
|
||||||
///
|
|
||||||
- (id) responseObjectForResponse:(NSURLResponse *)response
|
|
||||||
data:(NSData *)data
|
|
||||||
error:(NSError *__autoreleasing *)error {
|
|
||||||
NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error];
|
|
||||||
|
|
||||||
// if response data is not a valid json, return string of data.
|
|
||||||
if ([self isParseError:*error]) {
|
|
||||||
*error = nil;
|
|
||||||
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
|
||||||
return responseString;
|
|
||||||
}
|
|
||||||
|
|
||||||
return responseJson;
|
|
||||||
}
|
|
||||||
|
|
||||||
-(BOOL)isParseError:(NSError *)error {
|
|
||||||
return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840;
|
|
||||||
}
|
|
||||||
|
|
||||||
+ (instancetype)serializer {
|
|
||||||
return [self serializerWithReadingOptions:NSJSONReadingAllowFragments];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,8 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <AFNetworking/AFURLResponseSerialization.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer
|
|
||||||
|
|
||||||
@end
|
|
@ -1,8 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <JSONModel/JSONValueTransformer.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface JSONValueTransformer (ISO8601)
|
|
||||||
|
|
||||||
@end
|
|
@ -1,11 +0,0 @@
|
|||||||
#import <ISO8601/NSDate+ISO8601.h>
|
|
||||||
#import "JSONValueTransformer+ISO8601.h"
|
|
||||||
|
|
||||||
@implementation JSONValueTransformer (ISO8601)
|
|
||||||
|
|
||||||
- (NSDate *) NSDateFromNSString:(NSString *)string
|
|
||||||
{
|
|
||||||
return [NSDate dateWithISO8601String:string];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,42 +0,0 @@
|
|||||||
#import "{{classPrefix}}Object.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}Object
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Workaround for JSONModel multithreading issues
|
|
||||||
* https://github.com/icanzilb/JSONModel/issues/441
|
|
||||||
*/
|
|
||||||
- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err {
|
|
||||||
static NSMutableSet *classNames;
|
|
||||||
static dispatch_once_t onceToken;
|
|
||||||
dispatch_once(&onceToken, ^{
|
|
||||||
classNames = [NSMutableSet new];
|
|
||||||
});
|
|
||||||
|
|
||||||
BOOL initSync;
|
|
||||||
@synchronized([self class])
|
|
||||||
{
|
|
||||||
NSString *className = NSStringFromClass([self class]);
|
|
||||||
initSync = ![classNames containsObject:className];
|
|
||||||
if(initSync)
|
|
||||||
{
|
|
||||||
[classNames addObject:className];
|
|
||||||
self = [super initWithDictionary:dict error:err];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if(!initSync)
|
|
||||||
{
|
|
||||||
self = [super initWithDictionary:dict error:err];
|
|
||||||
}
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the string presentation of the object.
|
|
||||||
* This method will be called when logging model object using `NSLog`.
|
|
||||||
*/
|
|
||||||
- (NSString *)description {
|
|
||||||
return [[self toDictionary] description];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,8 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <JSONModel/JSONModel.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}Object : JSONModel
|
|
||||||
|
|
||||||
@end
|
|
@ -1,20 +0,0 @@
|
|||||||
#import "{{classPrefix}}QueryParamCollection.h"
|
|
||||||
|
|
||||||
@implementation {{classPrefix}}QueryParamCollection
|
|
||||||
|
|
||||||
@synthesize values = _values;
|
|
||||||
@synthesize format = _format;
|
|
||||||
|
|
||||||
- (id)initWithValuesAndFormat:(NSArray *)values
|
|
||||||
format:(NSString *)format {
|
|
||||||
|
|
||||||
self = [super init];
|
|
||||||
if (self) {
|
|
||||||
_values = values;
|
|
||||||
_format = format;
|
|
||||||
}
|
|
||||||
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,13 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
@interface {{classPrefix}}QueryParamCollection : NSObject
|
|
||||||
|
|
||||||
@property(nonatomic, readonly) NSArray* values;
|
|
||||||
@property(nonatomic, readonly) NSString* format;
|
|
||||||
|
|
||||||
- (id) initWithValuesAndFormat: (NSArray*) values
|
|
||||||
format: (NSString*) format;
|
|
||||||
|
|
||||||
@end
|
|
@ -1,143 +0,0 @@
|
|||||||
# {{podName}}
|
|
||||||
|
|
||||||
{{#appDescription}}
|
|
||||||
{{{appDescription}}}
|
|
||||||
{{/appDescription}}
|
|
||||||
|
|
||||||
This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project:
|
|
||||||
|
|
||||||
- API version: {{appVersion}}
|
|
||||||
- Package version: {{artifactVersion}}
|
|
||||||
- Build date: {{generatedDate}}
|
|
||||||
- Build package: {{generatorClass}}
|
|
||||||
{{#infoUrl}}
|
|
||||||
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
|
|
||||||
{{/infoUrl}}
|
|
||||||
|
|
||||||
## Requirements
|
|
||||||
|
|
||||||
The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.com/questions/7778356/how-to-enable-disable-automatic-reference-counting) to be enabled in the Xcode project.
|
|
||||||
|
|
||||||
## Installation & Usage
|
|
||||||
### Install from Github using [CocoaPods](https://cocoapods.org/)
|
|
||||||
|
|
||||||
Add the following to the Podfile:
|
|
||||||
|
|
||||||
```ruby
|
|
||||||
pod '{{podName}}', :git => 'https://github.com/{{gitUserId}}/{{gitRepoId}}.git'
|
|
||||||
```
|
|
||||||
|
|
||||||
To specify a particular branch, append `, :branch => 'branch-name-here'`
|
|
||||||
|
|
||||||
To specify a particular commit, append `, :commit => '11aa22'`
|
|
||||||
|
|
||||||
### Install from local path using [CocoaPods](https://cocoapods.org/)
|
|
||||||
|
|
||||||
Put the SDK under your project folder (e.g. /path/to/objc_project/Vendor/{{podName}}) and then add the following to the Podfile:
|
|
||||||
|
|
||||||
```ruby
|
|
||||||
pod '{{podName}}', :path => 'Vendor/{{podName}}'
|
|
||||||
```
|
|
||||||
|
|
||||||
### Usage
|
|
||||||
|
|
||||||
Import the following:
|
|
||||||
|
|
||||||
```objc
|
|
||||||
#import <{{podName}}/{{{classPrefix}}}ApiClient.h>
|
|
||||||
#import <{{podName}}/{{{classPrefix}}}Configuration.h>
|
|
||||||
// load models
|
|
||||||
{{#models}}{{#model}}#import <{{podName}}/{{{classname}}}.h>
|
|
||||||
{{/model}}{{/models}}// load API classes for accessing endpoints
|
|
||||||
{{#apiInfo}}{{#apis}}#import <{{podName}}/{{{classname}}}.h>
|
|
||||||
{{/apis}}{{/apiInfo}}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Recommendation
|
|
||||||
|
|
||||||
It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue.
|
|
||||||
|
|
||||||
## Getting Started
|
|
||||||
|
|
||||||
Please follow the [installation procedure](#installation--usage) and then run the following:
|
|
||||||
|
|
||||||
```objc
|
|
||||||
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
|
|
||||||
{{#hasAuthMethods}}
|
|
||||||
{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig];
|
|
||||||
{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}})
|
|
||||||
[apiConfig setUsername:@"YOUR_USERNAME"];
|
|
||||||
[apiConfig setPassword:@"YOUR_PASSWORD"];
|
|
||||||
{{/isBasic}}{{#isApiKey}}
|
|
||||||
// Configure API key authorization: (authentication scheme: {{{name}}})
|
|
||||||
[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"];
|
|
||||||
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
|
|
||||||
//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"];
|
|
||||||
{{/isApiKey}}{{#isOAuth}}
|
|
||||||
// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}})
|
|
||||||
[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
|
|
||||||
{{/isOAuth}}{{/authMethods}}
|
|
||||||
{{/hasAuthMethods}}
|
|
||||||
|
|
||||||
{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
|
|
||||||
{{/allParams}}
|
|
||||||
|
|
||||||
{{classname}} *apiInstance = [[{{classname}} alloc] init];
|
|
||||||
|
|
||||||
{{#summary}}// {{{.}}}
|
|
||||||
{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
|
|
||||||
{{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}}
|
|
||||||
{{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) {
|
|
||||||
{{#returnType}}
|
|
||||||
if (output) {
|
|
||||||
NSLog(@"%@", output);
|
|
||||||
}
|
|
||||||
{{/returnType}}
|
|
||||||
if (error) {
|
|
||||||
NSLog(@"Error: %@", error);
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 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}}
|
|
||||||
|
|
@ -1,161 +0,0 @@
|
|||||||
{{#operations}}
|
|
||||||
#import "{{classname}}.h"
|
|
||||||
#import "{{classPrefix}}QueryParamCollection.h"
|
|
||||||
{{#imports}}#import "{{import}}.h"
|
|
||||||
{{/imports}}
|
|
||||||
{{newline}}
|
|
||||||
|
|
||||||
@interface {{classname}} ()
|
|
||||||
|
|
||||||
@property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@implementation {{classname}}
|
|
||||||
|
|
||||||
NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain";
|
|
||||||
NSInteger k{{classname}}MissingParamErrorCode = 234513;
|
|
||||||
|
|
||||||
@synthesize sessionManager = _sessionManager;
|
|
||||||
|
|
||||||
#pragma mark - Initialize methods
|
|
||||||
|
|
||||||
- (id)initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager {
|
|
||||||
self = [super init];
|
|
||||||
if (self) {
|
|
||||||
_sessionManager = sessionManager;
|
|
||||||
_defaultHeaders = [NSMutableDictionary dictionary];
|
|
||||||
}
|
|
||||||
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark -
|
|
||||||
|
|
||||||
-(NSString*) defaultHeaderForKey:(NSString*)key {
|
|
||||||
return self.defaultHeaders[key];
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
|
|
||||||
[self setDefaultHeaderValue:value forKey:key];
|
|
||||||
}
|
|
||||||
|
|
||||||
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key {
|
|
||||||
[self.defaultHeaders setValue:value forKey:key];
|
|
||||||
}
|
|
||||||
|
|
||||||
#pragma mark - Api Methods
|
|
||||||
|
|
||||||
{{#operation}}
|
|
||||||
///
|
|
||||||
/// {{{summary}}}
|
|
||||||
/// {{{notes}}}
|
|
||||||
/// {{#allParams}} @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
|
|
||||||
///
|
|
||||||
/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
|
|
||||||
///
|
|
||||||
-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
|
|
||||||
{{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}}
|
|
||||||
{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler {
|
|
||||||
{{#allParams}}
|
|
||||||
{{#required}}
|
|
||||||
// verify the required parameter '{{paramName}}' is set
|
|
||||||
if ({{paramName}} == nil) {
|
|
||||||
NSParameterAssert({{paramName}});
|
|
||||||
if(handler) {
|
|
||||||
NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"{{paramName}}"] };
|
|
||||||
NSError* error = [NSError errorWithDomain:k{{classname}}ErrorDomain code:k{{classname}}MissingParamErrorCode userInfo:userInfo];
|
|
||||||
handler({{#returnType}}nil, {{/returnType}}error);
|
|
||||||
}
|
|
||||||
return nil;
|
|
||||||
}
|
|
||||||
|
|
||||||
{{/required}}
|
|
||||||
{{/allParams}}
|
|
||||||
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"];
|
|
||||||
|
|
||||||
// remove format in URL if needed
|
|
||||||
[resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)];
|
|
||||||
|
|
||||||
NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init];
|
|
||||||
{{#pathParams}}
|
|
||||||
if ({{paramName}} != nil) {
|
|
||||||
pathParams[@"{{baseName}}"] = {{paramName}};
|
|
||||||
}
|
|
||||||
{{/pathParams}}
|
|
||||||
|
|
||||||
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
|
|
||||||
{{#queryParams}}
|
|
||||||
if ({{paramName}} != nil) {
|
|
||||||
{{#collectionFormat}}
|
|
||||||
queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{paramName}} format: @"{{collectionFormat}}"];
|
|
||||||
{{/collectionFormat}}
|
|
||||||
{{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}}
|
|
||||||
}
|
|
||||||
{{/queryParams}}
|
|
||||||
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders];
|
|
||||||
[headerParams addEntriesFromDictionary:self.defaultHeaders];
|
|
||||||
{{#headerParams}}
|
|
||||||
if ({{paramName}} != nil) {
|
|
||||||
headerParams[@"{{baseName}}"] = {{paramName}};
|
|
||||||
}
|
|
||||||
{{/headerParams}}
|
|
||||||
// HTTP header `Accept`
|
|
||||||
NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]];
|
|
||||||
if(acceptHeader.length > 0) {
|
|
||||||
headerParams[@"Accept"] = acceptHeader;
|
|
||||||
}
|
|
||||||
|
|
||||||
// response content type
|
|
||||||
NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @"";
|
|
||||||
|
|
||||||
// request content type
|
|
||||||
NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]];
|
|
||||||
|
|
||||||
// Authentication setting
|
|
||||||
NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}];
|
|
||||||
|
|
||||||
id bodyParam = nil;
|
|
||||||
NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init];
|
|
||||||
NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init];
|
|
||||||
{{#bodyParam}}
|
|
||||||
bodyParam = {{paramName}};
|
|
||||||
{{/bodyParam}}
|
|
||||||
{{^bodyParam}}
|
|
||||||
{{#formParams}}
|
|
||||||
{{#notFile}}
|
|
||||||
if ({{paramName}}) {
|
|
||||||
formParams[@"{{baseName}}"] = {{paramName}};
|
|
||||||
}
|
|
||||||
{{/notFile}}
|
|
||||||
{{#isFile}}
|
|
||||||
localVarFiles[@"{{paramName}}"] = {{paramName}};
|
|
||||||
{{/isFile}}
|
|
||||||
{{/formParams}}
|
|
||||||
{{/bodyParam}}
|
|
||||||
|
|
||||||
return [self.sessionManager requestWithPath: resourcePath
|
|
||||||
method: @"{{httpMethod}}"
|
|
||||||
pathParams: pathParams
|
|
||||||
queryParams: queryParams
|
|
||||||
formParams: formParams
|
|
||||||
files: localVarFiles
|
|
||||||
body: bodyParam
|
|
||||||
headerParams: headerParams
|
|
||||||
authSettings: authSettings
|
|
||||||
requestContentType: requestContentType
|
|
||||||
responseContentType: responseContentType
|
|
||||||
responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}}
|
|
||||||
completionBlock: ^(id data, NSError *error) {
|
|
||||||
if(handler) {
|
|
||||||
handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
{{/operation}}
|
|
||||||
|
|
||||||
{{newline}}
|
|
||||||
{{/operations}}
|
|
||||||
@end
|
|
@ -1,34 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
{{#imports}}#import "{{import}}.h"
|
|
||||||
{{/imports}}
|
|
||||||
#import "{{classPrefix}}ApiSessionManager.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
|
|
||||||
@interface {{classname}}: NSObject <{{classPrefix}}Api>
|
|
||||||
|
|
||||||
extern NSString* k{{classname}}ErrorDomain;
|
|
||||||
extern NSInteger k{{classname}}MissingParamErrorCode;
|
|
||||||
|
|
||||||
+(instancetype) sharedAPI;
|
|
||||||
|
|
||||||
{{#operations}}
|
|
||||||
{{#operation}}
|
|
||||||
/// {{{summary}}}
|
|
||||||
/// {{#notes}}{{{notes}}}{{/notes}}
|
|
||||||
///
|
|
||||||
/// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
|
|
||||||
/// {{/allParams}}{{#responses}}
|
|
||||||
/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}}
|
|
||||||
///
|
|
||||||
/// @return {{{returnType}}}
|
|
||||||
-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
|
|
||||||
{{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}}
|
|
||||||
{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler;
|
|
||||||
|
|
||||||
{{newline}}
|
|
||||||
{{/operation}}
|
|
||||||
{{/operations}}
|
|
||||||
|
|
||||||
@end
|
|
@ -1,59 +0,0 @@
|
|||||||
{{#models}}
|
|
||||||
{{#model}}
|
|
||||||
#import "{{classname}}.h"
|
|
||||||
|
|
||||||
@implementation {{classname}}
|
|
||||||
|
|
||||||
- (instancetype)init {
|
|
||||||
self = [super init];
|
|
||||||
if (self) {
|
|
||||||
// initialize property's default value, if any
|
|
||||||
{{#vars}}{{#defaultValue}}self.{{name}} = {{{defaultValue}}};
|
|
||||||
{{/defaultValue}}{{/vars}}
|
|
||||||
}
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
{{#vars}}{{^vendorExtensions.x-unique-id-key}}{{/vendorExtensions.x-unique-id-key}}{{#vendorExtensions.x-unique-id-key}}
|
|
||||||
-(NSString*)indexPropertyName {
|
|
||||||
return @"{{name}}";
|
|
||||||
}
|
|
||||||
{{/vendorExtensions.x-unique-id-key}}{{/vars}}
|
|
||||||
{{#discriminator}}
|
|
||||||
/**
|
|
||||||
* Maps "discriminator" value to the sub-class name, so that inheritance is supported.
|
|
||||||
*/
|
|
||||||
- (id)initWithDictionary:(NSDictionary *)dict error:(NSError *__autoreleasing *)err {
|
|
||||||
NSString * discriminatedClassName = [dict valueForKey:@"{{discriminator}}"];
|
|
||||||
if(discriminatedClassName == nil ){
|
|
||||||
return [super initWithDictionary:dict error:err];
|
|
||||||
}
|
|
||||||
Class class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:discriminatedClassName]);
|
|
||||||
if([self class ] == class) {
|
|
||||||
return [super initWithDictionary:dict error:err];
|
|
||||||
}
|
|
||||||
return [[class alloc] initWithDictionary:dict error: err];
|
|
||||||
}
|
|
||||||
{{/discriminator}}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Maps json key to property name.
|
|
||||||
* This method is used by `JSONModel`.
|
|
||||||
*/
|
|
||||||
+ (JSONKeyMapper *)keyMapper {
|
|
||||||
return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Indicates whether the property with the given name is optional.
|
|
||||||
* If `propertyName` is optional, then return `YES`, otherwise return `NO`.
|
|
||||||
* This method is used by `JSONModel`.
|
|
||||||
*/
|
|
||||||
+ (BOOL)propertyIsOptional:(NSString *)propertyName {
|
|
||||||
|
|
||||||
NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}];
|
|
||||||
return [optionalProperties containsObject:propertyName];
|
|
||||||
}
|
|
||||||
|
|
||||||
{{/model}}
|
|
||||||
@end
|
|
||||||
{{/models}}
|
|
@ -1,25 +0,0 @@
|
|||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import "{{classPrefix}}Object.h"
|
|
||||||
|
|
||||||
{{>licenceInfo}}
|
|
||||||
|
|
||||||
{{#imports}}#import "{{import}}.h"
|
|
||||||
{{/imports}}
|
|
||||||
{{newline}}
|
|
||||||
{{#models}}
|
|
||||||
{{#model}}
|
|
||||||
|
|
||||||
@protocol {{classname}}
|
|
||||||
@end
|
|
||||||
|
|
||||||
@interface {{classname}} : {{#parent}}{{{parent}}}{{/parent}}{{^parent}}{{classPrefix}}Object{{/parent}}
|
|
||||||
|
|
||||||
{{#vars}}
|
|
||||||
{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}}
|
|
||||||
*/{{/description}}
|
|
||||||
@property(nonatomic) {{{ datatype }}} {{name}};
|
|
||||||
{{/vars}}
|
|
||||||
|
|
||||||
@end
|
|
||||||
{{/model}}
|
|
||||||
{{/models}}
|
|
@ -1,37 +0,0 @@
|
|||||||
#
|
|
||||||
# Be sure to run `pod lib lint {{podName}}.podspec' to ensure this is a
|
|
||||||
# valid spec and remove all comments before submitting the spec.
|
|
||||||
#
|
|
||||||
# Any lines starting with a # are optional, but encouraged
|
|
||||||
#
|
|
||||||
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
|
|
||||||
#
|
|
||||||
|
|
||||||
Pod::Spec.new do |s|
|
|
||||||
s.name = "{{podName}}"
|
|
||||||
s.version = "{{podVersion}}"
|
|
||||||
{{#apiInfo}}{{#apis}}{{^hasMore}}
|
|
||||||
s.summary = "{{appName}}"
|
|
||||||
s.description = <<-DESC
|
|
||||||
{{{appDescription}}}
|
|
||||||
DESC
|
|
||||||
{{/hasMore}}{{/apis}}{{/apiInfo}}
|
|
||||||
s.platform = :ios, '7.0'
|
|
||||||
s.requires_arc = true
|
|
||||||
|
|
||||||
{{^useCoreData}}s.framework = 'SystemConfiguration'{{/useCoreData}}{{#useCoreData}}s.frameworks = 'SystemConfiguration', 'CoreData'{{/useCoreData}}
|
|
||||||
|
|
||||||
s.homepage = "{{gitRepoURL}}"
|
|
||||||
s.license = "{{#license}}{{license}}{{/license}}{{^license}}Apache License, Version 2.0{{/license}}"
|
|
||||||
s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" }
|
|
||||||
s.author = { "{{authorName}}" => "{{authorEmail}}" }
|
|
||||||
|
|
||||||
s.source_files = '{{podName}}/**/*.{m,h}'
|
|
||||||
s.public_header_files = '{{podName}}/**/*.h'
|
|
||||||
{{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}}
|
|
||||||
|
|
||||||
s.dependency 'AFNetworking', '~> 3'
|
|
||||||
s.dependency 'JSONModel', '~> 1.2'
|
|
||||||
s.dependency 'ISO8601', '~> 0.5'
|
|
||||||
end
|
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user