Friday, 1 February 2019

Use Swagger Codegen to generate response models in Swift



JAVA environment

1. Download and install java JDK   https://www.oracle.com/technetwork/java/javase/downloads/index.html

2. Open ~/.bash_profile or create it if not exist, add these lines to .bash_profile
   export JAVA_HOME=`/usr/libexec/java_home`
   export PATH=$JAVA_HOME/bin:$PATH
   Save and quit. 

Echo $JAVA_HOME should print the “/Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home”
check java version:   java —version 



Swagger-codegen

Download a snapshot from 
https://oss.sonatype.org/content/repositories/snapshots/io/swagger/swagger-codegen-cli/2.3.0-SNAPSHOT/

Latest stable version:  swagger-codegen-cli-2.3.0-20171221.103805-388.jar
After downloading, try command: java -jar <path_to_the_jar_file>/swagger-codegen-…..-2.3.0.jar help




Docker to install swagger editor

1. Download and install Docker: https://store.docker.com
2. Run Docker
3. docker pull swaggerapi/swagger-ui
    docker pull swaggerapi/swagger-editor
    (Dock hub: https://hub.docker.com/r/swaggerapi/swagger-editor/)




Code generate

Try generate Swift models through this command:

            java -jar <swagger_codegen_jar_file_path>/swagger-codegen-2.3.0.jar generate 
                -c <swagger_config_file_path>/….SwaggerConfig.json 
                -i <yaml_file_path>/…..swagger.yaml 
                -l swift4 
                -o <output_directory_path>
                --type-mappings Double=Decimal

The structure of the output directory would be:






Copy the .podspec and the folder contains Classes to your project. It can be places just under the root folder, just depending on how you are organising your project structure.









Podfile

1. update podfile







2. pod install
    SylviaExampleClient will be imported to Pods





























Now you will be able to import the framework and use the models in your Swift code



Example swaggerconfig/yaml files and iOS project
Check: https://github.com/Sylvia-YiyinShen/SwaggerToSwift

No comments:

Post a Comment