Merge branch 'master' of github.com:wordnik/swagger-codegen

This commit is contained in:
Ivan Porto Carrero 2013-11-09 12:18:42 -08:00
commit b39a609226
250 changed files with 13277 additions and 4562 deletions

5
bin/Version.scala Normal file
View File

@ -0,0 +1,5 @@
val version = scala.util.Properties.scalaPropOrElse("version.number", "unknown").toString match {
case "2.10.0" => "2.10"
case e: String => e
}
println(version)

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -24,12 +25,8 @@ cd $APP_DIR
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" ags="$@ samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -24,12 +25,8 @@ cd $APP_DIR
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ samples/client/petstore/csharp/CsharpPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" ags="$@ samples/client/petstore/csharp/CsharpPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -21,14 +22,11 @@ cd $APP_DIR
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties "
ags="$@ samples/client/petstore/flash/FlashPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" ags="$@ samples/client/petstore/flash/FlashPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -24,12 +25,8 @@ cd $APP_DIR
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DfileMap=src/test/resources/petstore-1.1/resources.json -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DfileMap=src/test/resources/petstore-1.1/resources.json -DloggerPath=conf/log4j.properties"
ags="$@ samples/client/petstore/java/JavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" ags="$@ samples/client/petstore/java/JavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -24,12 +25,8 @@ cd $APP_DIR
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ samples/client/petstore/java/JavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" ags="$@ samples/client/petstore/java/JavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -21,15 +22,11 @@ cd $APP_DIR
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files/resources.json"
ags="$@ samples/client/wordnik-api/java/JavaWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" ags="$@ samples/client/wordnik-api/java/JavaWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,9 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
version="$(scala ./bin/Version.scala)"
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -24,12 +27,8 @@ cd $APP_DIR
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ samples/client/petstore/objc/ObjcPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" ags="$@ samples/client/petstore/objc/ObjcPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -24,12 +25,8 @@ cd $APP_DIR
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files"
ags="$@ samples/client/wordnik-api/objc/ObjcWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" ags="$@ samples/client/wordnik-api/objc/ObjcWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -24,12 +25,8 @@ cd $APP_DIR
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ samples/client/petstore/php/PHPPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" ags="$@ samples/client/petstore/php/PHPPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -21,15 +22,11 @@ cd $APP_DIR
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files/resources.json"
ags="$@ samples/client/wordnik-api/php/PHPWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" ags="$@ samples/client/wordnik-api/php/PHPWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -24,12 +25,8 @@ cd $APP_DIR
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ samples/client/petstore/python/PythonPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" ags="$@ samples/client/petstore/python/PythonPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -21,14 +22,11 @@ cd $APP_DIR
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files/resources.json"
ags="$@ samples/client/wordnik-api/python/PythonWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" ags="$@ samples/client/wordnik-api/python/PythonWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -24,12 +25,8 @@ cd $APP_DIR
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ samples/client/petstore/python3/Python3PetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" ags="$@ samples/client/petstore/python3/Python3PetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -21,15 +22,11 @@ cd $APP_DIR
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files/resources.json"
ags="$@ samples/client/wordnik-api/python3/Python3WordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" ags="$@ samples/client/wordnik-api/python3/Python3WordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -24,12 +25,8 @@ cd $APP_DIR
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ samples/client/petstore/ruby/RubyPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" ags="$@ samples/client/petstore/ruby/RubyPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -24,12 +25,8 @@ cd $APP_DIR
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@" ags="$@"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -23,10 +24,8 @@ cd $APP_DIR
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
ags="com.wordnik.swagger.codegen.ScalaAsyncClientGenerator $@" ags="com.wordnik.swagger.codegen.ScalaAsyncClientGenerator $@"
if [ -f $APP_DIR/target/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
java -cp target/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
else else
./sbt "run-main $ags" echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -24,11 +25,8 @@ cd $APP_DIR
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ samples/client/petstore/scala/ScalaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" ags="$@ samples/client/petstore/scala/ScalaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -21,14 +22,11 @@ cd $APP_DIR
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files/resources.json"
ags="$@ samples/client/wordnik-api/scala/ScalaWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" ags="$@ samples/client/wordnik-api/scala/ScalaWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
scala -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt assembly echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
scala -cp target/swagger-codegen.jar $ags
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -24,11 +25,8 @@ cd $APP_DIR
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files"
ags="$@ SwaggerDocGenerator http://developer.wordnik.com/v4/resources.json" ags="$@ SwaggerDocGenerator http://developer.wordnik.com/v4/resources.json"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
java -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt "run-main $ags" echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -23,11 +24,8 @@ cd $APP_DIR
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
ags="com.wordnik.swagger.codegen.SpecConverter $@" ags="com.wordnik.swagger.codegen.SpecConverter $@"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
java -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt "run-main $ags" echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
fi fi

View File

@ -1,6 +1,7 @@
#!/bin/sh #!/bin/sh
SCRIPT="$0" SCRIPT="$0"
SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala)
while [ -h "$SCRIPT" ] ; do while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"` ls=`ls -ld "$SCRIPT"`
@ -23,11 +24,8 @@ cd $APP_DIR
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
ags="com.wordnik.swagger.codegen.spec.Validator $@" ags="com.wordnik.swagger.codegen.spec.Validator $@"
if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then
scala -cp target/scala-2.9.1/swagger-codegen.jar $ags scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags
elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then
java -cp target/scala-2.10/swagger-codegen.jar $ags
else else
./sbt "run-main $ags" echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly"
fi fi

View File

@ -5,9 +5,9 @@ organization := "com.wordnik"
name := "swagger-codegen" name := "swagger-codegen"
version := "2.0.10-SNAPSHOT" version := "2.0.11"
scalaVersion := "2.10.0" scalaVersion := "2.9.1"
javacOptions ++= Seq("-target", "1.6", "-source", "1.6", "-Xlint:unchecked", "-Xlint:deprecation") javacOptions ++= Seq("-target", "1.6", "-source", "1.6", "-Xlint:unchecked", "-Xlint:deprecation")

View File

@ -26,7 +26,7 @@
/// </summary> /// </summary>
/// <param name="petId">ID of pet that needs to be fetched</param> /// <param name="petId">ID of pet that needs to be fetched</param>
/// <returns></returns> /// <returns></returns>
public Pet getPetById (string petId) { public Pet getPetById (long petId) {
// create path and map variables // create path and map variables
var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(petId.ToString())); var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(petId.ToString()));
@ -92,6 +92,111 @@
} }
} }
/// <summary> /// <summary>
/// partial updates to a pet
/// </summary>
/// <param name="petId">ID of pet that needs to be fetched</param>
/// <param name="body">Pet object that needs to be added to the store</param>
/// <returns></returns>
public Array<Pet> partialUpdate (string petId, Pet body) {
// create path and map variables
var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(petId.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (petId == null || body == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiInvoker.invokeAPI(basePath, path, "PATCH", queryParams, body, headerParams);
if(response != null){
return (Array<Pet>) ApiInvoker.deserialize(response, typeof(Array<Pet>));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name="petId">ID of pet that needs to be updated</param>
/// <param name="name">Updated name of the pet</param>
/// <param name="status">Updated status of the pet</param>
/// <returns></returns>
public void updatePetWithForm (string petId, string name, string status) {
// create path and map variables
var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(petId.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (petId == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return ;
}
else {
throw ex;
}
}
}
/// <summary>
/// uploads an image
/// </summary>
/// <param name="additionalMetadata">Additional data to pass to server</param>
/// <param name="body">file to upload</param>
/// <returns></returns>
public void uploadFile (string additionalMetadata, File body) {
// create path and map variables
var path = "/pet/uploadImage".Replace("{format}","json");
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
string paramStr = null;
try {
var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return ;
}
else {
throw ex;
}
}
}
/// <summary>
/// Add a new pet to the store /// Add a new pet to the store
/// </summary> /// </summary>
/// <param name="body">Pet object that needs to be added to the store</param> /// <param name="body">Pet object that needs to be added to the store</param>
@ -166,7 +271,7 @@
/// </summary> /// </summary>
/// <param name="status">Status values that need to be considered for filter</param> /// <param name="status">Status values that need to be considered for filter</param>
/// <returns></returns> /// <returns></returns>
public List<Pet> findPetsByStatus (string status) { public Array<Pet> findPetsByStatus (string status) {
// create path and map variables // create path and map variables
var path = "/pet/findByStatus".Replace("{format}","json"); var path = "/pet/findByStatus".Replace("{format}","json");
@ -186,7 +291,7 @@
try { try {
var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams);
if(response != null){ if(response != null){
return (List<Pet>) ApiInvoker.deserialize(response, typeof(List<Pet>)); return (Array<Pet>) ApiInvoker.deserialize(response, typeof(Array<Pet>));
} }
else { else {
return null; return null;
@ -205,7 +310,7 @@
/// </summary> /// </summary>
/// <param name="tags">Tags to filter by</param> /// <param name="tags">Tags to filter by</param>
/// <returns></returns> /// <returns></returns>
public List<Pet> findPetsByTags (string tags) { public Array<Pet> findPetsByTags (string tags) {
// create path and map variables // create path and map variables
var path = "/pet/findByTags".Replace("{format}","json"); var path = "/pet/findByTags".Replace("{format}","json");
@ -225,7 +330,7 @@
try { try {
var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams);
if(response != null){ if(response != null){
return (List<Pet>) ApiInvoker.deserialize(response, typeof(List<Pet>)); return (Array<Pet>) ApiInvoker.deserialize(response, typeof(Array<Pet>));
} }
else { else {
return null; return null;

View File

@ -61,7 +61,7 @@
/// </summary> /// </summary>
/// <param name="body">List of user object</param> /// <param name="body">List of user object</param>
/// <returns></returns> /// <returns></returns>
public void createUsersWithArrayInput (array<User> body) { public void createUsersWithArrayInput (List<User> body) {
// create path and map variables // create path and map variables
var path = "/user/createWithArray".Replace("{format}","json"); var path = "/user/createWithArray".Replace("{format}","json");
@ -96,7 +96,7 @@
/// </summary> /// </summary>
/// <param name="body">List of user object</param> /// <param name="body">List of user object</param>
/// <returns></returns> /// <returns></returns>
public void createUsersWithListInput (array<User> body) { public void createUsersWithListInput (List<User> body) {
// create path and map variables // create path and map variables
var path = "/user/createWithList".Replace("{format}","json"); var path = "/user/createWithList".Replace("{format}","json");

View File

@ -5,15 +5,17 @@ using System.Collections.Generic;
namespace Com.Wordnik.Petstore.Model { namespace Com.Wordnik.Petstore.Model {
public class Category { public class Category {
public string name { get; set; } /* Category unique identifier */
public long id { get; set; } public long id { get; set; }
/* Name of the category */
public string name { get; set; }
public override string ToString() { public override string ToString() {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class Category {\n"); sb.Append("class Category {\n");
sb.Append(" name: ").Append(name).Append("\n");
sb.Append(" id: ").Append(id).Append("\n"); sb.Append(" id: ").Append(id).Append("\n");
sb.Append(" name: ").Append(name).Append("\n");
sb.Append("}\n"); sb.Append("}\n");
return sb.ToString(); return sb.ToString();
} }

View File

@ -5,24 +5,28 @@ using System.Collections.Generic;
namespace Com.Wordnik.Petstore.Model { namespace Com.Wordnik.Petstore.Model {
public class Order { public class Order {
/* Unique identifier for the order */
public long id { get; set; } public long id { get; set; }
/* Order Status */ /* ID of pet being ordered */
public string status { get; set; }
public long petId { get; set; } public long petId { get; set; }
/* Number of pets ordered */
public int quantity { get; set; } public int quantity { get; set; }
/* Status of the order */
public string status { get; set; }
/* Date shipped, only if it has been */
public DateTime shipDate { get; set; } public DateTime shipDate { get; set; }
public override string ToString() { public override string ToString() {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class Order {\n"); sb.Append("class Order {\n");
sb.Append(" id: ").Append(id).Append("\n"); sb.Append(" id: ").Append(id).Append("\n");
sb.Append(" status: ").Append(status).Append("\n");
sb.Append(" petId: ").Append(petId).Append("\n"); sb.Append(" petId: ").Append(petId).Append("\n");
sb.Append(" quantity: ").Append(quantity).Append("\n"); sb.Append(" quantity: ").Append(quantity).Append("\n");
sb.Append(" status: ").Append(status).Append("\n");
sb.Append(" shipDate: ").Append(shipDate).Append("\n"); sb.Append(" shipDate: ").Append(shipDate).Append("\n");
sb.Append("}\n"); sb.Append("}\n");
return sb.ToString(); return sb.ToString();

View File

@ -5,28 +5,33 @@ using System.Collections.Generic;
namespace Com.Wordnik.Petstore.Model { namespace Com.Wordnik.Petstore.Model {
public class Pet { public class Pet {
public string name { get; set; } /* Unique identifier for the Pet */
public long id { get; set; } public long id { get; set; }
/* Category the pet is in */
public Category category { get; set; }
/* Friendly name of the pet */
public string name { get; set; }
/* Image URLs */
public List<string> photoUrls { get; set; }
/* Tags assigned to this pet */
public List<Tag> tags { get; set; } public List<Tag> tags { get; set; }
/* pet status in the store */ /* pet status in the store */
public string status { get; set; } public string status { get; set; }
public List<string> photoUrls { get; set; }
public Category category { get; set; }
public override string ToString() { public override string ToString() {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class Pet {\n"); sb.Append("class Pet {\n");
sb.Append(" name: ").Append(name).Append("\n");
sb.Append(" id: ").Append(id).Append("\n"); sb.Append(" id: ").Append(id).Append("\n");
sb.Append(" category: ").Append(category).Append("\n");
sb.Append(" name: ").Append(name).Append("\n");
sb.Append(" photoUrls: ").Append(photoUrls).Append("\n");
sb.Append(" tags: ").Append(tags).Append("\n"); sb.Append(" tags: ").Append(tags).Append("\n");
sb.Append(" status: ").Append(status).Append("\n"); sb.Append(" status: ").Append(status).Append("\n");
sb.Append(" photoUrls: ").Append(photoUrls).Append("\n");
sb.Append(" category: ").Append(category).Append("\n");
sb.Append("}\n"); sb.Append("}\n");
return sb.ToString(); return sb.ToString();
} }

View File

@ -5,15 +5,17 @@ using System.Collections.Generic;
namespace Com.Wordnik.Petstore.Model { namespace Com.Wordnik.Petstore.Model {
public class Tag { public class Tag {
public string name { get; set; } /* Unique identifier for the tag */
public long id { get; set; } public long id { get; set; }
/* Friendly name for the tag */
public string name { get; set; }
public override string ToString() { public override string ToString() {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class Tag {\n"); sb.Append("class Tag {\n");
sb.Append(" name: ").Append(name).Append("\n");
sb.Append(" id: ").Append(id).Append("\n"); sb.Append(" id: ").Append(id).Append("\n");
sb.Append(" name: ").Append(name).Append("\n");
sb.Append("}\n"); sb.Append("}\n");
return sb.ToString(); return sb.ToString();
} }

View File

@ -5,18 +5,25 @@ using System.Collections.Generic;
namespace Com.Wordnik.Petstore.Model { namespace Com.Wordnik.Petstore.Model {
public class User { public class User {
/* Unique identifier for the user */
public long id { get; set; } public long id { get; set; }
public string firstName { get; set; } /* Unique username */
public string username { get; set; } public string username { get; set; }
/* First name of the user */
public string firstName { get; set; }
/* Last name of the user */
public string lastName { get; set; } public string lastName { get; set; }
/* Email address of the user */
public string email { get; set; } public string email { get; set; }
/* Password name of the user */
public string password { get; set; } public string password { get; set; }
/* Phone number of the user */
public string phone { get; set; } public string phone { get; set; }
/* User Status */ /* User Status */
@ -26,8 +33,8 @@ namespace Com.Wordnik.Petstore.Model {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class User {\n"); sb.Append("class User {\n");
sb.Append(" id: ").Append(id).Append("\n"); sb.Append(" id: ").Append(id).Append("\n");
sb.Append(" firstName: ").Append(firstName).Append("\n");
sb.Append(" username: ").Append(username).Append("\n"); sb.Append(" username: ").Append(username).Append("\n");
sb.Append(" firstName: ").Append(firstName).Append("\n");
sb.Append(" lastName: ").Append(lastName).Append("\n"); sb.Append(" lastName: ").Append(lastName).Append("\n");
sb.Append(" email: ").Append(email).Append("\n"); sb.Append(" email: ").Append(email).Append("\n");
sb.Append(" password: ").Append(password).Append("\n"); sb.Append(" password: ").Append(password).Append("\n");

View File

@ -7,6 +7,7 @@ import com.wordnik.swagger.common.ApiUserCredentials;
import com.wordnik.swagger.event.Response; import com.wordnik.swagger.event.Response;
import com.wordnik.swagger.common.SwaggerApi; import com.wordnik.swagger.common.SwaggerApi;
import com.wordnik.client.model.Pet; import com.wordnik.client.model.Pet;
import com.wordnik.client.model.File;
import mx.rpc.AsyncToken; import mx.rpc.AsyncToken;
import mx.utils.UIDUtil; import mx.utils.UIDUtil;
import flash.utils.Dictionary; import flash.utils.Dictionary;
@ -23,15 +24,19 @@ public class PetApi extends SwaggerApi {
} }
public static const event_getPetById: String = "getPetById"; public static const event_getPetById: String = "getPetById";
public static const event_deletePet: String = "deletePet";
public static const event_partialUpdate: String = "partialUpdate";
public static const event_updatePetWithForm: String = "updatePetWithForm";
public static const event_uploadFile: String = "uploadFile";
public static const event_addPet: String = "addPet"; public static const event_addPet: String = "addPet";
public static const event_updatePet: String = "updatePet"; public static const event_updatePet: String = "updatePet";
public static const event_findPetsByStatus: String = "findPetsByStatus"; public static const event_findPetsByStatus: String = "findPetsByStatus";
public static const event_findPetsByTags: String = "findPetsByTags"; public static const event_findPetsByTags: String = "findPetsByTags";
/* /*
* Returns Pet */ * Returns Pet */
public function getPetById (petId: String): String { public function getPetById (petId: Number): String {
// create path and map variables // create path and map variables
var path: String = "/pet.{format}/{petId}".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); var path: String = "/pet/{petId}".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId));
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();
@ -51,12 +56,108 @@ public static const event_findPetsByTags: String = "findPetsByTags";
token.returnType = Pet; token.returnType = Pet;
return requestId; return requestId;
}
/*
* Returns void */
public function deletePet (petId: String): String {
// create path and map variables
var path: String = "/pet/{petId}".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId));
// query params
var queryParams: Dictionary = new Dictionary();
var headerParams: Dictionary = new Dictionary();
// verify required params are set
if(petId == null ) {
throw new ApiError(400, "missing required params");
}
var token:AsyncToken = getApiInvoker().invokeAPI(path, "DELETE", queryParams, null, headerParams);
var requestId: String = getUniqueId();
token.requestId = requestId;
token.completionEventType = "deletePet";
token.returnType = null ;
return requestId;
}
/*
* Returns Array[Pet] */
public function partialUpdate (petId: String, body: Pet): String {
// create path and map variables
var path: String = "/pet/{petId}".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId));
// query params
var queryParams: Dictionary = new Dictionary();
var headerParams: Dictionary = new Dictionary();
// verify required params are set
if(petId == null || body == null ) {
throw new ApiError(400, "missing required params");
}
var token:AsyncToken = getApiInvoker().invokeAPI(path, "PATCH", queryParams, body, headerParams);
var requestId: String = getUniqueId();
token.requestId = requestId;
token.completionEventType = "partialUpdate";
token.returnType = Array[Pet];
return requestId;
}
/*
* Returns void */
public function updatePetWithForm (petId: String, name: String, status: String): String {
// create path and map variables
var path: String = "/pet/{petId}".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId));
// query params
var queryParams: Dictionary = new Dictionary();
var headerParams: Dictionary = new Dictionary();
// verify required params are set
if(petId == null ) {
throw new ApiError(400, "missing required params");
}
var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, null, headerParams);
var requestId: String = getUniqueId();
token.requestId = requestId;
token.completionEventType = "updatePetWithForm";
token.returnType = null ;
return requestId;
}
/*
* Returns void */
public function uploadFile (additionalMetadata: String, body: File): String {
// create path and map variables
var path: String = "/pet/uploadImage".replace(/{format}/g,"xml");
// query params
var queryParams: Dictionary = new Dictionary();
var headerParams: Dictionary = new Dictionary();
var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams);
var requestId: String = getUniqueId();
token.requestId = requestId;
token.completionEventType = "uploadFile";
token.returnType = null ;
return requestId;
} }
/* /*
* Returns void */ * Returns void */
public function addPet (body: Pet): String { public function addPet (body: Pet): String {
// create path and map variables // create path and map variables
var path: String = "/pet.{format}".replace(/{format}/g,"xml"); var path: String = "/pet".replace(/{format}/g,"xml");
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();
@ -81,7 +182,7 @@ public static const event_findPetsByTags: String = "findPetsByTags";
* Returns void */ * Returns void */
public function updatePet (body: Pet): String { public function updatePet (body: Pet): String {
// create path and map variables // create path and map variables
var path: String = "/pet.{format}".replace(/{format}/g,"xml"); var path: String = "/pet".replace(/{format}/g,"xml");
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();
@ -103,10 +204,10 @@ public static const event_findPetsByTags: String = "findPetsByTags";
} }
/* /*
* Returns com.wordnik.client.model.PetList */ * Returns Array[Pet] */
public function findPetsByStatus (status: String= "available"): String { public function findPetsByStatus (status: String= "available"): String {
// create path and map variables // create path and map variables
var path: String = "/pet.{format}/findByStatus".replace(/{format}/g,"xml"); var path: String = "/pet/findByStatus".replace(/{format}/g,"xml");
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();
@ -125,15 +226,15 @@ public static const event_findPetsByTags: String = "findPetsByTags";
token.requestId = requestId; token.requestId = requestId;
token.completionEventType = "findPetsByStatus"; token.completionEventType = "findPetsByStatus";
token.returnType = com.wordnik.client.model.PetList; token.returnType = Array[Pet];
return requestId; return requestId;
} }
/* /*
* Returns com.wordnik.client.model.PetList */ * Returns Array[Pet] */
public function findPetsByTags (tags: String): String { public function findPetsByTags (tags: String): String {
// create path and map variables // create path and map variables
var path: String = "/pet.{format}/findByTags".replace(/{format}/g,"xml"); var path: String = "/pet/findByTags".replace(/{format}/g,"xml");
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();
@ -152,7 +253,7 @@ public static const event_findPetsByTags: String = "findPetsByTags";
token.requestId = requestId; token.requestId = requestId;
token.completionEventType = "findPetsByTags"; token.completionEventType = "findPetsByTags";
token.returnType = com.wordnik.client.model.PetList; token.returnType = Array[Pet];
return requestId; return requestId;
} }

View File

@ -29,7 +29,7 @@ public static const event_placeOrder: String = "placeOrder";
* Returns Order */ * Returns Order */
public function getOrderById (orderId: String): String { public function getOrderById (orderId: String): String {
// create path and map variables // create path and map variables
var path: String = "/store.{format}/order/{orderId}".replace(/{format}/g,"xml").replace("{" + "orderId" + "}", getApiInvoker().escapeString(orderId)); var path: String = "/store/order/{orderId}".replace(/{format}/g,"xml").replace("{" + "orderId" + "}", getApiInvoker().escapeString(orderId));
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();
@ -54,7 +54,7 @@ public static const event_placeOrder: String = "placeOrder";
* Returns void */ * Returns void */
public function deleteOrder (orderId: String): String { public function deleteOrder (orderId: String): String {
// create path and map variables // create path and map variables
var path: String = "/store.{format}/order/{orderId}".replace(/{format}/g,"xml").replace("{" + "orderId" + "}", getApiInvoker().escapeString(orderId)); var path: String = "/store/order/{orderId}".replace(/{format}/g,"xml").replace("{" + "orderId" + "}", getApiInvoker().escapeString(orderId));
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();
@ -79,7 +79,7 @@ public static const event_placeOrder: String = "placeOrder";
* Returns void */ * Returns void */
public function placeOrder (body: Order): String { public function placeOrder (body: Order): String {
// create path and map variables // create path and map variables
var path: String = "/store.{format}/order".replace(/{format}/g,"xml"); var path: String = "/store/order".replace(/{format}/g,"xml");
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();

View File

@ -22,44 +22,19 @@ public class UserApi extends SwaggerApi {
super(apiCredentials, eventDispatcher); super(apiCredentials, eventDispatcher);
} }
public static const event_createUsersWithArrayInput: String = "createUsersWithArrayInput";
public static const event_createUser: String = "createUser"; public static const event_createUser: String = "createUser";
public static const event_createUsersWithArrayInput: String = "createUsersWithArrayInput";
public static const event_createUsersWithListInput: String = "createUsersWithListInput"; public static const event_createUsersWithListInput: String = "createUsersWithListInput";
public static const event_updateUser: String = "updateUser"; public static const event_updateUser: String = "updateUser";
public static const event_deleteUser: String = "deleteUser"; public static const event_deleteUser: String = "deleteUser";
public static const event_getUserByName: String = "getUserByName"; public static const event_getUserByName: String = "getUserByName";
public static const event_loginUser: String = "loginUser"; public static const event_loginUser: String = "loginUser";
public static const event_logoutUser: String = "logoutUser"; public static const event_logoutUser: String = "logoutUser";
/*
* Returns void */
public function createUsersWithArrayInput (body: Array): String {
// create path and map variables
var path: String = "/user.{format}/createWithArray".replace(/{format}/g,"xml");
// query params
var queryParams: Dictionary = new Dictionary();
var headerParams: Dictionary = new Dictionary();
// verify required params are set
if(body == null ) {
throw new ApiError(400, "missing required params");
}
var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams);
var requestId: String = getUniqueId();
token.requestId = requestId;
token.completionEventType = "createUsersWithArrayInput";
token.returnType = null ;
return requestId;
}
/* /*
* Returns void */ * Returns void */
public function createUser (body: User): String { public function createUser (body: User): String {
// create path and map variables // create path and map variables
var path: String = "/user.{format}".replace(/{format}/g,"xml"); var path: String = "/user".replace(/{format}/g,"xml");
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();
@ -79,12 +54,37 @@ public static const event_logoutUser: String = "logoutUser";
token.returnType = null ; token.returnType = null ;
return requestId; return requestId;
}
/*
* Returns void */
public function createUsersWithArrayInput (body: Array): String {
// create path and map variables
var path: String = "/user/createWithArray".replace(/{format}/g,"xml");
// query params
var queryParams: Dictionary = new Dictionary();
var headerParams: Dictionary = new Dictionary();
// verify required params are set
if(body == null ) {
throw new ApiError(400, "missing required params");
}
var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams);
var requestId: String = getUniqueId();
token.requestId = requestId;
token.completionEventType = "createUsersWithArrayInput";
token.returnType = null ;
return requestId;
} }
/* /*
* Returns void */ * Returns void */
public function createUsersWithListInput (body: Array): String { public function createUsersWithListInput (body: Array): String {
// create path and map variables // create path and map variables
var path: String = "/user.{format}/createWithList".replace(/{format}/g,"xml"); var path: String = "/user/createWithList".replace(/{format}/g,"xml");
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();
@ -109,7 +109,7 @@ public static const event_logoutUser: String = "logoutUser";
* Returns void */ * Returns void */
public function updateUser (username: String, body: User): String { public function updateUser (username: String, body: User): String {
// create path and map variables // create path and map variables
var path: String = "/user.{format}/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); var path: String = "/user/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username));
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();
@ -134,7 +134,7 @@ public static const event_logoutUser: String = "logoutUser";
* Returns void */ * Returns void */
public function deleteUser (username: String): String { public function deleteUser (username: String): String {
// create path and map variables // create path and map variables
var path: String = "/user.{format}/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); var path: String = "/user/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username));
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();
@ -159,7 +159,7 @@ public static const event_logoutUser: String = "logoutUser";
* Returns User */ * Returns User */
public function getUserByName (username: String): String { public function getUserByName (username: String): String {
// create path and map variables // create path and map variables
var path: String = "/user.{format}/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); var path: String = "/user/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username));
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();
@ -184,7 +184,7 @@ public static const event_logoutUser: String = "logoutUser";
* Returns string */ * Returns string */
public function loginUser (username: String, password: String): String { public function loginUser (username: String, password: String): String {
// create path and map variables // create path and map variables
var path: String = "/user.{format}/login".replace(/{format}/g,"xml"); var path: String = "/user/login".replace(/{format}/g,"xml");
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();
@ -213,7 +213,7 @@ public static const event_logoutUser: String = "logoutUser";
* Returns void */ * Returns void */
public function logoutUser (): String { public function logoutUser (): String {
// create path and map variables // create path and map variables
var path: String = "/user.{format}/logout".replace(/{format}/g,"xml"); var path: String = "/user/logout".replace(/{format}/g,"xml");
// query params // query params
var queryParams: Dictionary = new Dictionary(); var queryParams: Dictionary = new Dictionary();

View File

@ -2,9 +2,11 @@ package com.wordnik.client.model {
[XmlRootNode(name="Category")] [XmlRootNode(name="Category")]
public class Category { public class Category {
/* Category unique identifier */
[XmlElement(name="id")] [XmlElement(name="id")]
public var id: Number = 0.0; public var id: Number = 0.0;
/* Name of the category */
[XmlElement(name="name")] [XmlElement(name="name")]
public var name: String = null; public var name: String = null;

View File

@ -2,19 +2,23 @@ package com.wordnik.client.model {
[XmlRootNode(name="Order")] [XmlRootNode(name="Order")]
public class Order { public class Order {
/* Unique identifier for the order */
[XmlElement(name="id")] [XmlElement(name="id")]
public var id: Number = 0.0; public var id: Number = 0.0;
/* ID of pet being ordered */
[XmlElement(name="petId")] [XmlElement(name="petId")]
public var petId: Number = 0.0; public var petId: Number = 0.0;
/* Order Status */ /* Number of pets ordered */
[XmlElement(name="status")]
public var status: String = null;
[XmlElement(name="quantity")] [XmlElement(name="quantity")]
public var quantity: Number = 0.0; public var quantity: Number = 0.0;
/* Status of the order */
[XmlElement(name="status")]
public var status: String = null;
/* Date shipped, only if it has been */
[XmlElement(name="shipDate")] [XmlElement(name="shipDate")]
public var shipDate: Date = null; public var shipDate: Date = null;
@ -22,8 +26,8 @@ package com.wordnik.client.model {
var str: String = "Order: "; var str: String = "Order: ";
str += " (id: " + id + ")"; str += " (id: " + id + ")";
str += " (petId: " + petId + ")"; str += " (petId: " + petId + ")";
str += " (status: " + status + ")";
str += " (quantity: " + quantity + ")"; str += " (quantity: " + quantity + ")";
str += " (status: " + status + ")";
str += " (shipDate: " + shipDate + ")"; str += " (shipDate: " + shipDate + ")";
return str; return str;
} }

View File

@ -4,39 +4,44 @@ import com.wordnik.client.model.Category;
import com.wordnik.client.model.Tag; import com.wordnik.client.model.Tag;
[XmlRootNode(name="Pet")] [XmlRootNode(name="Pet")]
public class Pet { public class Pet {
// This declaration below of _tags_obj_class is to force flash compiler to include this class /* Unique identifier for the Pet */
private var _tags_obj_class: com.wordnik.client.model.Tag = null;
[XmlElementWrapper(name="tags")]
[XmlElements(name="tag", type="com.wordnik.client.model.Tag")]
public var tags: Array = new Array();
[XmlElement(name="id")] [XmlElement(name="id")]
public var id: Number = 0.0; public var id: Number = 0.0;
/* Category the pet is in */
[XmlElement(name="category")] [XmlElement(name="category")]
public var category: Category = null; public var category: Category = null;
/* pet status in the store */ /* Friendly name of the pet */
[XmlElement(name="status")]
public var status: String = null;
[XmlElement(name="name")] [XmlElement(name="name")]
public var name: String = null; public var name: String = null;
/* Image URLs */
// This declaration below of _photoUrls_obj_class is to force flash compiler to include this class // This declaration below of _photoUrls_obj_class is to force flash compiler to include this class
private var _photoUrls_obj_class: com.wordnik.client.model.String = null; private var _photoUrls_obj_class: com.wordnik.client.model.String = null;
[XmlElementWrapper(name="photoUrls")] [XmlElementWrapper(name="photoUrls")]
[XmlElements(name="photoUrl", type="com.wordnik.client.model.String")] [XmlElements(name="photoUrl", type="com.wordnik.client.model.String")]
public var photoUrls: Array = new Array(); public var photoUrls: Array = new Array();
/* Tags assigned to this pet */
// This declaration below of _tags_obj_class is to force flash compiler to include this class
private var _tags_obj_class: com.wordnik.client.model.Tag = null;
[XmlElementWrapper(name="tags")]
[XmlElements(name="tag", type="com.wordnik.client.model.Tag")]
public var tags: Array = new Array();
/* pet status in the store */
[XmlElement(name="status")]
public var status: String = null;
public function toString(): String { public function toString(): String {
var str: String = "Pet: "; var str: String = "Pet: ";
str += " (tags: " + tags + ")";
str += " (id: " + id + ")"; str += " (id: " + id + ")";
str += " (category: " + category + ")"; str += " (category: " + category + ")";
str += " (status: " + status + ")";
str += " (name: " + name + ")"; str += " (name: " + name + ")";
str += " (photoUrls: " + photoUrls + ")"; str += " (photoUrls: " + photoUrls + ")";
str += " (tags: " + tags + ")";
str += " (status: " + status + ")";
return str; return str;
} }

View File

@ -2,9 +2,11 @@ package com.wordnik.client.model {
[XmlRootNode(name="Tag")] [XmlRootNode(name="Tag")]
public class Tag { public class Tag {
/* Unique identifier for the tag */
[XmlElement(name="id")] [XmlElement(name="id")]
public var id: Number = 0.0; public var id: Number = 0.0;
/* Friendly name for the tag */
[XmlElement(name="name")] [XmlElement(name="name")]
public var name: String = null; public var name: String = null;

View File

@ -2,41 +2,48 @@ package com.wordnik.client.model {
[XmlRootNode(name="User")] [XmlRootNode(name="User")]
public class User { public class User {
/* Unique identifier for the user */
[XmlElement(name="id")] [XmlElement(name="id")]
public var id: Number = 0.0; public var id: Number = 0.0;
[XmlElement(name="lastName")] /* Unique username */
public var lastName: String = null;
[XmlElement(name="phone")]
public var phone: String = null;
[XmlElement(name="username")] [XmlElement(name="username")]
public var username: String = null; public var username: String = null;
/* First name of the user */
[XmlElement(name="firstName")]
public var firstName: String = null;
/* Last name of the user */
[XmlElement(name="lastName")]
public var lastName: String = null;
/* Email address of the user */
[XmlElement(name="email")] [XmlElement(name="email")]
public var email: String = null; public var email: String = null;
/* Password name of the user */
[XmlElement(name="password")]
public var password: String = null;
/* Phone number of the user */
[XmlElement(name="phone")]
public var phone: String = null;
/* User Status */ /* User Status */
[XmlElement(name="userStatus")] [XmlElement(name="userStatus")]
public var userStatus: Number = 0.0; public var userStatus: Number = 0.0;
[XmlElement(name="firstName")]
public var firstName: String = null;
[XmlElement(name="password")]
public var password: String = null;
public function toString(): String { public function toString(): String {
var str: String = "User: "; var str: String = "User: ";
str += " (id: " + id + ")"; str += " (id: " + id + ")";
str += " (lastName: " + lastName + ")";
str += " (phone: " + phone + ")";
str += " (username: " + username + ")"; str += " (username: " + username + ")";
str += " (email: " + email + ")";
str += " (userStatus: " + userStatus + ")";
str += " (firstName: " + firstName + ")"; str += " (firstName: " + firstName + ")";
str += " (lastName: " + lastName + ")";
str += " (email: " + email + ")";
str += " (password: " + password + ")"; str += " (password: " + password + ")";
str += " (phone: " + phone + ")";
str += " (userStatus: " + userStatus + ")";
return str; return str;
} }

View File

@ -20,20 +20,25 @@ object ObjcPetstoreCodegen extends BasicObjcGenerator {
def main(args: Array[String]) = generateClient(args) def main(args: Array[String]) = generateClient(args)
// where to write generated code // where to write generated code
override def destinationDir = "samples/client/petstore/objc/client" val outputFolder = "samples/client/petstore/objc/"
override def destinationDir = outputFolder + java.io.File.separator + "client"
// to avoid recompiling ... // to avoid recompiling ...
override def templateDir = "src/main/resources/objc" override def templateDir = "objc"
additionalParams ++= Map("projectName" -> "PetstoreClient")
// supporting classes // supporting classes
override def supportingFiles = override def supportingFiles =
List( List(
("NIKSwaggerObject.h", destinationDir, "NIKSwaggerObject.h"), ("SWGObject.h", destinationDir, "SWGObject.h"),
("NIKSwaggerObject.m", destinationDir, "NIKSwaggerObject.m"), ("SWGObject.m", destinationDir, "SWGObject.m"),
("NIKApiInvoker.h", destinationDir, "NIKApiInvoker.h"), ("SWGApiClient.h", destinationDir, "SWGApiClient.h"),
("NIKApiInvoker.m", destinationDir, "NIKApiInvoker.m"), ("SWGApiClient.m", destinationDir, "SWGApiClient.m"),
("NIKFile.h", destinationDir, "NIKFile.h"), ("SWGFile.h", destinationDir, "SWGFile.h"),
("NIKFile.m", destinationDir, "NIKFile.m"), ("SWGFile.m", destinationDir, "SWGFile.m"),
("NIKDate.h", destinationDir, "NIKDate.h"), ("SWGDate.h", destinationDir, "SWGDate.h"),
("NIKDate.m", destinationDir, "NIKDate.m")) ("SWGDate.m", destinationDir, "SWGDate.m"),
("Podfile.mustache", outputFolder, "Podfile")
)
} }

View File

@ -0,0 +1 @@
<?xml version='1.0' encoding='UTF-8'?><Workspace version='1.0'><FileRef location='group:PetstoreClient/PetstoreClient.xcodeproj'/><FileRef location='group:Pods/Pods.xcodeproj'/></Workspace>

View File

@ -0,0 +1,41 @@
<?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>IDESourceControlProjectFavoriteDictionaryKey</key>
<false/>
<key>IDESourceControlProjectIdentifier</key>
<string>81EB09FA-DD8C-4FE1-82D3-1FB6FF0D9C43</string>
<key>IDESourceControlProjectName</key>
<string>PetstoreClient</string>
<key>IDESourceControlProjectOriginsDictionary</key>
<dict>
<key>92840518-904D-4771-AA3D-9AF52CA48B71</key>
<string>ssh://github.com/wordnik/swagger-codegen.git</string>
</dict>
<key>IDESourceControlProjectPath</key>
<string>samples/client/petstore/objc/PetstoreClient.xcworkspace</string>
<key>IDESourceControlProjectRelativeInstallPathDictionary</key>
<dict>
<key>92840518-904D-4771-AA3D-9AF52CA48B71</key>
<string>../../../../..</string>
</dict>
<key>IDESourceControlProjectURL</key>
<string>ssh://github.com/wordnik/swagger-codegen.git</string>
<key>IDESourceControlProjectVersion</key>
<integer>110</integer>
<key>IDESourceControlProjectWCCIdentifier</key>
<string>92840518-904D-4771-AA3D-9AF52CA48B71</string>
<key>IDESourceControlProjectWCConfigurations</key>
<array>
<dict>
<key>IDESourceControlRepositoryExtensionIdentifierKey</key>
<string>public.vcs.git</string>
<key>IDESourceControlWCCIdentifierKey</key>
<string>92840518-904D-4771-AA3D-9AF52CA48B71</string>
<key>IDESourceControlWCCName</key>
<string>swagger-codegen</string>
</dict>
</array>
</dict>
</plist>

View File

@ -7,233 +7,245 @@
objects = { objects = {
/* Begin PBXBuildFile section */ /* Begin PBXBuildFile section */
EA07F4BE16134F27006A2112 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA07F4BD16134F27006A2112 /* Foundation.framework */; }; BA525648922D4C0E9F44D4F1 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 73DA4F1067C343C3962F1542 /* libPods.a */; };
EA07F4C116134F27006A2112 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = EA07F4C016134F27006A2112 /* main.m */; }; EA66999A1811D2FA00A70D03 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA6699991811D2FA00A70D03 /* Foundation.framework */; };
EA07F4C516134F27006A2112 /* PetstoreClient.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = EA07F4C416134F27006A2112 /* PetstoreClient.1 */; }; EA66999C1811D2FA00A70D03 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA66999B1811D2FA00A70D03 /* CoreGraphics.framework */; };
EA07F5311613580E006A2112 /* SenTestingKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA07F5301613580E006A2112 /* SenTestingKit.framework */; }; EA66999E1811D2FA00A70D03 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA66999D1811D2FA00A70D03 /* UIKit.framework */; };
EA07F53316135819006A2112 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA07F53216135819006A2112 /* Cocoa.framework */; }; EA6699A41811D2FA00A70D03 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = EA6699A21811D2FA00A70D03 /* InfoPlist.strings */; };
EA4F4D3816F1A90A00F24B35 /* NIKFile.m in Sources */ = {isa = PBXBuildFile; fileRef = EA4F4D3716F1A90A00F24B35 /* NIKFile.m */; }; EA6699A61811D2FA00A70D03 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = EA6699A51811D2FA00A70D03 /* main.m */; };
EAE9042217BF2F7900486EFE /* NIKApiInvoker.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040617BF2F3A00486EFE /* NIKApiInvoker.h */; }; EA6699AA1811D2FA00A70D03 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = EA6699A91811D2FA00A70D03 /* AppDelegate.m */; };
EAE9042317BF2F7900486EFE /* NIKApiInvoker.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040717BF2F3A00486EFE /* NIKApiInvoker.m */; }; EA6699AD1811D2FA00A70D03 /* Main_iPhone.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = EA6699AB1811D2FA00A70D03 /* Main_iPhone.storyboard */; };
EAE9042417BF2F7900486EFE /* NIKDate.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040817BF2F3A00486EFE /* NIKDate.h */; }; EA6699B01811D2FA00A70D03 /* Main_iPad.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = EA6699AE1811D2FA00A70D03 /* Main_iPad.storyboard */; };
EAE9042517BF2F7900486EFE /* NIKDate.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040917BF2F3A00486EFE /* NIKDate.m */; }; EA6699B31811D2FA00A70D03 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = EA6699B21811D2FA00A70D03 /* ViewController.m */; };
EAE9042617BF2F7900486EFE /* NIKSwaggerObject.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040A17BF2F3A00486EFE /* NIKSwaggerObject.h */; }; EA6699B51811D2FA00A70D03 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = EA6699B41811D2FA00A70D03 /* Images.xcassets */; };
EAE9042717BF2F7900486EFE /* NIKSwaggerObject.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040B17BF2F3A00486EFE /* NIKSwaggerObject.m */; }; EA6699BC1811D2FB00A70D03 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA6699BB1811D2FB00A70D03 /* XCTest.framework */; };
EAE9042817BF2F7900486EFE /* RVBCategory.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE903F617BF2CB200486EFE /* RVBCategory.h */; }; EA6699BD1811D2FB00A70D03 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA6699991811D2FA00A70D03 /* Foundation.framework */; };
EAE9042917BF2F7900486EFE /* RVBCategory.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE903F717BF2CB200486EFE /* RVBCategory.m */; }; EA6699BE1811D2FB00A70D03 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA66999D1811D2FA00A70D03 /* UIKit.framework */; };
EAE9042A17BF2F7900486EFE /* RVBOrder.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE903F817BF2CB200486EFE /* RVBOrder.h */; }; EA6699C61811D2FB00A70D03 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = EA6699C41811D2FB00A70D03 /* InfoPlist.strings */; };
EAE9042B17BF2F7900486EFE /* RVBOrder.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE903F917BF2CB200486EFE /* RVBOrder.m */; }; EA6699C81811D2FB00A70D03 /* PetstoreClientTests.m in Sources */ = {isa = PBXBuildFile; fileRef = EA6699C71811D2FB00A70D03 /* PetstoreClientTests.m */; };
EAE9042C17BF2F7900486EFE /* RVBPet.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE903FA17BF2CB200486EFE /* RVBPet.h */; }; EAEA85E41811D3AE00F06E69 /* SWGApiClient.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */; };
EAE9042D17BF2F7900486EFE /* RVBPet.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE903FB17BF2CB200486EFE /* RVBPet.m */; }; EAEA85E51811D3AE00F06E69 /* SWGCategory.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85CF1811D3AE00F06E69 /* SWGCategory.m */; };
EAE9042E17BF2F7900486EFE /* RVBPetApi.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE903FC17BF2CB200486EFE /* RVBPetApi.h */; }; EAEA85E61811D3AE00F06E69 /* SWGDate.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D11811D3AE00F06E69 /* SWGDate.m */; };
EAE9042F17BF2F7900486EFE /* RVBPetApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE903FD17BF2CB200486EFE /* RVBPetApi.m */; }; EAEA85E71811D3AE00F06E69 /* SWGFile.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D31811D3AE00F06E69 /* SWGFile.m */; };
EAE9043017BF2F7900486EFE /* RVBStoreApi.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE903FE17BF2CB200486EFE /* RVBStoreApi.h */; }; EAEA85E81811D3AE00F06E69 /* SWGObject.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D51811D3AE00F06E69 /* SWGObject.m */; };
EAE9043117BF2F7900486EFE /* RVBStoreApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE903FF17BF2CB200486EFE /* RVBStoreApi.m */; }; EAEA85E91811D3AE00F06E69 /* SWGOrder.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D71811D3AE00F06E69 /* SWGOrder.m */; };
EAE9043217BF2F7900486EFE /* RVBTag.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040017BF2CB200486EFE /* RVBTag.h */; }; EAEA85EA1811D3AE00F06E69 /* SWGPet.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D91811D3AE00F06E69 /* SWGPet.m */; };
EAE9043317BF2F7900486EFE /* RVBTag.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040117BF2CB200486EFE /* RVBTag.m */; }; EAEA85EB1811D3AE00F06E69 /* SWGPetApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85DB1811D3AE00F06E69 /* SWGPetApi.m */; };
EAE9043417BF2F7900486EFE /* RVBUser.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040217BF2CB200486EFE /* RVBUser.h */; }; EAEA85EC1811D3AE00F06E69 /* SWGStoreApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85DD1811D3AE00F06E69 /* SWGStoreApi.m */; };
EAE9043517BF2F7900486EFE /* RVBUser.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040317BF2CB200486EFE /* RVBUser.m */; }; EAEA85ED1811D3AE00F06E69 /* SWGTag.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85DF1811D3AE00F06E69 /* SWGTag.m */; };
EAE9043617BF2F7900486EFE /* RVBUserApi.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040417BF2CB200486EFE /* RVBUserApi.h */; }; EAEA85EE1811D3AE00F06E69 /* SWGUser.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85E11811D3AE00F06E69 /* SWGUser.m */; };
EAE9043717BF2F7900486EFE /* RVBUserApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040517BF2CB200486EFE /* RVBUserApi.m */; }; EAEA85EF1811D3AE00F06E69 /* SWGUserApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85E31811D3AE00F06E69 /* SWGUserApi.m */; };
EAE9043817BF318800486EFE /* NIKFile.h in Sources */ = {isa = PBXBuildFile; fileRef = EA4F4D3616F1A90A00F24B35 /* NIKFile.h */; }; EAEA85F11811D8F100F06E69 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = EAEA85F01811D8F100F06E69 /* libPods.a */; };
EAE9043917BF318800486EFE /* NIKFile.m in Sources */ = {isa = PBXBuildFile; fileRef = EA4F4D3716F1A90A00F24B35 /* NIKFile.m */; };
EAE9043A17BF31C800486EFE /* PetApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = EA81837816137FD500341A6E /* PetApiTest.m */; };
EAE9043B17BF31C800486EFE /* PetApiTest.h in Sources */ = {isa = PBXBuildFile; fileRef = EA81837916137FD500341A6E /* PetApiTest.h */; };
EAE9043C17BF31C800486EFE /* UserApiTest.h in Sources */ = {isa = PBXBuildFile; fileRef = EA5A034216141443003B3E41 /* UserApiTest.h */; };
EAE9043D17BF31C800486EFE /* UserApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = EA5A034316141443003B3E41 /* UserApiTest.m */; };
/* End PBXBuildFile section */ /* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */ /* Begin PBXContainerItemProxy section */
EA07F52E161357A5006A2112 /* PBXContainerItemProxy */ = { EA6699BF1811D2FB00A70D03 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy; isa = PBXContainerItemProxy;
containerPortal = EA07F4B016134F27006A2112 /* Project object */; containerPortal = EA66998E1811D2FA00A70D03 /* Project object */;
proxyType = 1; proxyType = 1;
remoteGlobalIDString = EA07F4B816134F27006A2112; remoteGlobalIDString = EA6699951811D2FA00A70D03;
remoteInfo = PetstoreClient; remoteInfo = PetstoreClient;
}; };
/* End PBXContainerItemProxy section */ /* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
EA07F4B716134F27006A2112 /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = /usr/share/man/man1/;
dstSubfolderSpec = 0;
files = (
EA07F4C516134F27006A2112 /* PetstoreClient.1 in CopyFiles */,
);
runOnlyForDeploymentPostprocessing = 1;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
EA07F4B916134F27006A2112 /* PetstoreClient */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = PetstoreClient; sourceTree = BUILT_PRODUCTS_DIR; }; 73DA4F1067C343C3962F1542 /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; };
EA07F4BD16134F27006A2112 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.xcconfig; path = ../Pods/Pods.xcconfig; sourceTree = "<group>"; };
EA07F4C016134F27006A2112 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; }; EA6699961811D2FA00A70D03 /* PetstoreClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PetstoreClient.app; sourceTree = BUILT_PRODUCTS_DIR; };
EA07F4C316134F27006A2112 /* PetstoreClient-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-Prefix.pch"; sourceTree = "<group>"; }; EA6699991811D2FA00A70D03 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
EA07F4C416134F27006A2112 /* PetstoreClient.1 */ = {isa = PBXFileReference; lastKnownFileType = text.man; path = PetstoreClient.1; sourceTree = "<group>"; }; EA66999B1811D2FA00A70D03 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
EA07F4F21613521A006A2112 /* PetstoreClientTests.octest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PetstoreClientTests.octest; sourceTree = BUILT_PRODUCTS_DIR; }; EA66999D1811D2FA00A70D03 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
EA07F5301613580E006A2112 /* SenTestingKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SenTestingKit.framework; path = Library/Frameworks/SenTestingKit.framework; sourceTree = DEVELOPER_DIR; }; EA6699A11811D2FA00A70D03 /* PetstoreClient-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "PetstoreClient-Info.plist"; sourceTree = "<group>"; };
EA07F53216135819006A2112 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; }; EA6699A31811D2FA00A70D03 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
EA4F4D3616F1A90A00F24B35 /* NIKFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = NIKFile.h; path = ../client/NIKFile.h; sourceTree = "<group>"; }; EA6699A51811D2FA00A70D03 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
EA4F4D3716F1A90A00F24B35 /* NIKFile.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = NIKFile.m; path = ../client/NIKFile.m; sourceTree = "<group>"; }; EA6699A71811D2FA00A70D03 /* PetstoreClient-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-Prefix.pch"; sourceTree = "<group>"; };
EA5A034216141443003B3E41 /* UserApiTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = UserApiTest.h; path = ../tests/UserApiTest.h; sourceTree = "<group>"; }; EA6699A81811D2FA00A70D03 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
EA5A034316141443003B3E41 /* UserApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = UserApiTest.m; path = ../tests/UserApiTest.m; sourceTree = "<group>"; }; EA6699A91811D2FA00A70D03 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };
EA81837816137FD500341A6E /* PetApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = PetApiTest.m; path = ../tests/PetApiTest.m; sourceTree = "<group>"; }; EA6699AC1811D2FA00A70D03 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main_iPhone.storyboard; sourceTree = "<group>"; };
EA81837916137FD500341A6E /* PetApiTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PetApiTest.h; path = ../tests/PetApiTest.h; sourceTree = "<group>"; }; EA6699AF1811D2FA00A70D03 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main_iPad.storyboard; sourceTree = "<group>"; };
EAE903F617BF2CB200486EFE /* RVBCategory.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBCategory.h; path = ../client/RVBCategory.h; sourceTree = "<group>"; }; EA6699B11811D2FA00A70D03 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = "<group>"; };
EAE903F717BF2CB200486EFE /* RVBCategory.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBCategory.m; path = ../client/RVBCategory.m; sourceTree = "<group>"; }; EA6699B21811D2FA00A70D03 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = "<group>"; };
EAE903F817BF2CB200486EFE /* RVBOrder.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBOrder.h; path = ../client/RVBOrder.h; sourceTree = "<group>"; }; EA6699B41811D2FA00A70D03 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = "<group>"; };
EAE903F917BF2CB200486EFE /* RVBOrder.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBOrder.m; path = ../client/RVBOrder.m; sourceTree = "<group>"; }; EA6699BA1811D2FB00A70D03 /* PetstoreClientTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PetstoreClientTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
EAE903FA17BF2CB200486EFE /* RVBPet.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBPet.h; path = ../client/RVBPet.h; sourceTree = "<group>"; }; EA6699BB1811D2FB00A70D03 /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; };
EAE903FB17BF2CB200486EFE /* RVBPet.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBPet.m; path = ../client/RVBPet.m; sourceTree = "<group>"; }; EA6699C31811D2FB00A70D03 /* PetstoreClientTests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "PetstoreClientTests-Info.plist"; sourceTree = "<group>"; };
EAE903FC17BF2CB200486EFE /* RVBPetApi.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBPetApi.h; path = ../client/RVBPetApi.h; sourceTree = "<group>"; }; EA6699C51811D2FB00A70D03 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
EAE903FD17BF2CB200486EFE /* RVBPetApi.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBPetApi.m; path = ../client/RVBPetApi.m; sourceTree = "<group>"; }; EA6699C71811D2FB00A70D03 /* PetstoreClientTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = PetstoreClientTests.m; sourceTree = "<group>"; };
EAE903FE17BF2CB200486EFE /* RVBStoreApi.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBStoreApi.h; path = ../client/RVBStoreApi.h; sourceTree = "<group>"; }; EAEA85CC1811D3AE00F06E69 /* SWGApiClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGApiClient.h; sourceTree = "<group>"; };
EAE903FF17BF2CB200486EFE /* RVBStoreApi.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBStoreApi.m; path = ../client/RVBStoreApi.m; sourceTree = "<group>"; }; EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiClient.m; sourceTree = "<group>"; };
EAE9040017BF2CB200486EFE /* RVBTag.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBTag.h; path = ../client/RVBTag.h; sourceTree = "<group>"; }; EAEA85CE1811D3AE00F06E69 /* SWGCategory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGCategory.h; sourceTree = "<group>"; };
EAE9040117BF2CB200486EFE /* RVBTag.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBTag.m; path = ../client/RVBTag.m; sourceTree = "<group>"; }; EAEA85CF1811D3AE00F06E69 /* SWGCategory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGCategory.m; sourceTree = "<group>"; };
EAE9040217BF2CB200486EFE /* RVBUser.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBUser.h; path = ../client/RVBUser.h; sourceTree = "<group>"; }; EAEA85D01811D3AE00F06E69 /* SWGDate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGDate.h; sourceTree = "<group>"; };
EAE9040317BF2CB200486EFE /* RVBUser.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBUser.m; path = ../client/RVBUser.m; sourceTree = "<group>"; }; EAEA85D11811D3AE00F06E69 /* SWGDate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGDate.m; sourceTree = "<group>"; };
EAE9040417BF2CB200486EFE /* RVBUserApi.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBUserApi.h; path = ../client/RVBUserApi.h; sourceTree = "<group>"; }; EAEA85D21811D3AE00F06E69 /* SWGFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGFile.h; sourceTree = "<group>"; };
EAE9040517BF2CB200486EFE /* RVBUserApi.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBUserApi.m; path = ../client/RVBUserApi.m; sourceTree = "<group>"; }; EAEA85D31811D3AE00F06E69 /* SWGFile.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGFile.m; sourceTree = "<group>"; };
EAE9040617BF2F3A00486EFE /* NIKApiInvoker.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = NIKApiInvoker.h; path = ../client/NIKApiInvoker.h; sourceTree = "<group>"; }; EAEA85D41811D3AE00F06E69 /* SWGObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGObject.h; sourceTree = "<group>"; };
EAE9040717BF2F3A00486EFE /* NIKApiInvoker.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = NIKApiInvoker.m; path = ../client/NIKApiInvoker.m; sourceTree = "<group>"; }; EAEA85D51811D3AE00F06E69 /* SWGObject.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGObject.m; sourceTree = "<group>"; };
EAE9040817BF2F3A00486EFE /* NIKDate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = NIKDate.h; path = ../client/NIKDate.h; sourceTree = "<group>"; }; EAEA85D61811D3AE00F06E69 /* SWGOrder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGOrder.h; sourceTree = "<group>"; };
EAE9040917BF2F3A00486EFE /* NIKDate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = NIKDate.m; path = ../client/NIKDate.m; sourceTree = "<group>"; }; EAEA85D71811D3AE00F06E69 /* SWGOrder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGOrder.m; sourceTree = "<group>"; };
EAE9040A17BF2F3A00486EFE /* NIKSwaggerObject.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = NIKSwaggerObject.h; path = ../client/NIKSwaggerObject.h; sourceTree = "<group>"; }; EAEA85D81811D3AE00F06E69 /* SWGPet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGPet.h; sourceTree = "<group>"; };
EAE9040B17BF2F3A00486EFE /* NIKSwaggerObject.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = NIKSwaggerObject.m; path = ../client/NIKSwaggerObject.m; sourceTree = "<group>"; }; EAEA85D91811D3AE00F06E69 /* SWGPet.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGPet.m; sourceTree = "<group>"; };
EAEA85DA1811D3AE00F06E69 /* SWGPetApi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGPetApi.h; sourceTree = "<group>"; };
EAEA85DB1811D3AE00F06E69 /* SWGPetApi.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGPetApi.m; sourceTree = "<group>"; };
EAEA85DC1811D3AE00F06E69 /* SWGStoreApi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGStoreApi.h; sourceTree = "<group>"; };
EAEA85DD1811D3AE00F06E69 /* SWGStoreApi.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGStoreApi.m; sourceTree = "<group>"; };
EAEA85DE1811D3AE00F06E69 /* SWGTag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGTag.h; sourceTree = "<group>"; };
EAEA85DF1811D3AE00F06E69 /* SWGTag.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGTag.m; sourceTree = "<group>"; };
EAEA85E01811D3AE00F06E69 /* SWGUser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGUser.h; sourceTree = "<group>"; };
EAEA85E11811D3AE00F06E69 /* SWGUser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGUser.m; sourceTree = "<group>"; };
EAEA85E21811D3AE00F06E69 /* SWGUserApi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGUserApi.h; sourceTree = "<group>"; };
EAEA85E31811D3AE00F06E69 /* SWGUserApi.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGUserApi.m; sourceTree = "<group>"; };
EAEA85F01811D8F100F06E69 /* libPods.a */ = {isa = PBXFileReference; lastKnownFileType = file; name = libPods.a; path = "../Pods/build/Debug-iphoneos/libPods.a"; sourceTree = "<group>"; };
/* End PBXFileReference section */ /* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */ /* Begin PBXFrameworksBuildPhase section */
EA07F4B616134F27006A2112 /* Frameworks */ = { EA6699931811D2FA00A70D03 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase; isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
EA07F4BE16134F27006A2112 /* Foundation.framework in Frameworks */, EA66999C1811D2FA00A70D03 /* CoreGraphics.framework in Frameworks */,
EA66999E1811D2FA00A70D03 /* UIKit.framework in Frameworks */,
EA66999A1811D2FA00A70D03 /* Foundation.framework in Frameworks */,
BA525648922D4C0E9F44D4F1 /* libPods.a in Frameworks */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
EA07F4EE1613521A006A2112 /* Frameworks */ = { EA6699B71811D2FB00A70D03 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase; isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
EA07F53316135819006A2112 /* Cocoa.framework in Frameworks */, EAEA85F11811D8F100F06E69 /* libPods.a in Frameworks */,
EA07F5311613580E006A2112 /* SenTestingKit.framework in Frameworks */, EA6699BC1811D2FB00A70D03 /* XCTest.framework in Frameworks */,
EA6699BE1811D2FB00A70D03 /* UIKit.framework in Frameworks */,
EA6699BD1811D2FB00A70D03 /* Foundation.framework in Frameworks */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
/* End PBXFrameworksBuildPhase section */ /* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */ /* Begin PBXGroup section */
EA07F4AE16134F27006A2112 = { EA66998D1811D2FA00A70D03 = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
EA81837C1613809300341A6E /* Tests */, EAEA85CB1811D3AE00F06E69 /* client */,
EA07F52D1613569E006A2112 /* Generated Client */, EA66999F1811D2FA00A70D03 /* PetstoreClient */,
EA07F4BF16134F27006A2112 /* PetstoreClient */, EA6699C11811D2FB00A70D03 /* PetstoreClientTests */,
EA07F4BC16134F27006A2112 /* Frameworks */, EA6699981811D2FA00A70D03 /* Frameworks */,
EA07F4BA16134F27006A2112 /* Products */, EA6699971811D2FA00A70D03 /* Products */,
EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */,
); );
sourceTree = "<group>"; sourceTree = "<group>";
}; };
EA07F4BA16134F27006A2112 /* Products */ = { EA6699971811D2FA00A70D03 /* Products */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
EA07F4B916134F27006A2112 /* PetstoreClient */, EA6699961811D2FA00A70D03 /* PetstoreClient.app */,
EA07F4F21613521A006A2112 /* PetstoreClientTests.octest */, EA6699BA1811D2FB00A70D03 /* PetstoreClientTests.xctest */,
); );
name = Products; name = Products;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
EA07F4BC16134F27006A2112 /* Frameworks */ = { EA6699981811D2FA00A70D03 /* Frameworks */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
EA07F53216135819006A2112 /* Cocoa.framework */, EAEA85F01811D8F100F06E69 /* libPods.a */,
EA07F5301613580E006A2112 /* SenTestingKit.framework */, EA6699991811D2FA00A70D03 /* Foundation.framework */,
EA07F4BD16134F27006A2112 /* Foundation.framework */, EA66999B1811D2FA00A70D03 /* CoreGraphics.framework */,
EA07F4F71613521A006A2112 /* Other Frameworks */, EA66999D1811D2FA00A70D03 /* UIKit.framework */,
EA6699BB1811D2FB00A70D03 /* XCTest.framework */,
73DA4F1067C343C3962F1542 /* libPods.a */,
); );
name = Frameworks; name = Frameworks;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
EA07F4BF16134F27006A2112 /* PetstoreClient */ = { EA66999F1811D2FA00A70D03 /* PetstoreClient */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
EA07F4C016134F27006A2112 /* main.m */, EA6699A81811D2FA00A70D03 /* AppDelegate.h */,
EA07F4C416134F27006A2112 /* PetstoreClient.1 */, EA6699A91811D2FA00A70D03 /* AppDelegate.m */,
EA07F4C216134F27006A2112 /* Supporting Files */, EA6699AB1811D2FA00A70D03 /* Main_iPhone.storyboard */,
EA6699AE1811D2FA00A70D03 /* Main_iPad.storyboard */,
EA6699B11811D2FA00A70D03 /* ViewController.h */,
EA6699B21811D2FA00A70D03 /* ViewController.m */,
EA6699B41811D2FA00A70D03 /* Images.xcassets */,
EA6699A01811D2FA00A70D03 /* Supporting Files */,
); );
path = PetstoreClient; path = PetstoreClient;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
EA07F4C216134F27006A2112 /* Supporting Files */ = { EA6699A01811D2FA00A70D03 /* Supporting Files */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
EA07F4C316134F27006A2112 /* PetstoreClient-Prefix.pch */, EA6699A11811D2FA00A70D03 /* PetstoreClient-Info.plist */,
EA6699A21811D2FA00A70D03 /* InfoPlist.strings */,
EA6699A51811D2FA00A70D03 /* main.m */,
EA6699A71811D2FA00A70D03 /* PetstoreClient-Prefix.pch */,
); );
name = "Supporting Files"; name = "Supporting Files";
sourceTree = "<group>"; sourceTree = "<group>";
}; };
EA07F4F71613521A006A2112 /* Other Frameworks */ = { EA6699C11811D2FB00A70D03 /* PetstoreClientTests */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
EA6699C71811D2FB00A70D03 /* PetstoreClientTests.m */,
EA6699C21811D2FB00A70D03 /* Supporting Files */,
); );
name = "Other Frameworks"; path = PetstoreClientTests;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
EA07F52D1613569E006A2112 /* Generated Client */ = { EA6699C21811D2FB00A70D03 /* Supporting Files */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
EAE9040617BF2F3A00486EFE /* NIKApiInvoker.h */, EA6699C31811D2FB00A70D03 /* PetstoreClientTests-Info.plist */,
EAE9040717BF2F3A00486EFE /* NIKApiInvoker.m */, EA6699C41811D2FB00A70D03 /* InfoPlist.strings */,
EAE9040817BF2F3A00486EFE /* NIKDate.h */,
EAE9040917BF2F3A00486EFE /* NIKDate.m */,
EA4F4D3616F1A90A00F24B35 /* NIKFile.h */,
EA4F4D3716F1A90A00F24B35 /* NIKFile.m */,
EAE9040A17BF2F3A00486EFE /* NIKSwaggerObject.h */,
EAE9040B17BF2F3A00486EFE /* NIKSwaggerObject.m */,
EAE903F617BF2CB200486EFE /* RVBCategory.h */,
EAE903F717BF2CB200486EFE /* RVBCategory.m */,
EAE903F817BF2CB200486EFE /* RVBOrder.h */,
EAE903F917BF2CB200486EFE /* RVBOrder.m */,
EAE903FA17BF2CB200486EFE /* RVBPet.h */,
EAE903FB17BF2CB200486EFE /* RVBPet.m */,
EAE903FC17BF2CB200486EFE /* RVBPetApi.h */,
EAE903FD17BF2CB200486EFE /* RVBPetApi.m */,
EAE903FE17BF2CB200486EFE /* RVBStoreApi.h */,
EAE903FF17BF2CB200486EFE /* RVBStoreApi.m */,
EAE9040017BF2CB200486EFE /* RVBTag.h */,
EAE9040117BF2CB200486EFE /* RVBTag.m */,
EAE9040217BF2CB200486EFE /* RVBUser.h */,
EAE9040317BF2CB200486EFE /* RVBUser.m */,
EAE9040417BF2CB200486EFE /* RVBUserApi.h */,
EAE9040517BF2CB200486EFE /* RVBUserApi.m */,
); );
name = "Generated Client"; name = "Supporting Files";
sourceTree = "<group>"; sourceTree = "<group>";
}; };
EA81837C1613809300341A6E /* Tests */ = { EAEA85CB1811D3AE00F06E69 /* client */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
EA81837816137FD500341A6E /* PetApiTest.m */, EAEA85CC1811D3AE00F06E69 /* SWGApiClient.h */,
EA81837916137FD500341A6E /* PetApiTest.h */, EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */,
EA5A034216141443003B3E41 /* UserApiTest.h */, EAEA85CE1811D3AE00F06E69 /* SWGCategory.h */,
EA5A034316141443003B3E41 /* UserApiTest.m */, EAEA85CF1811D3AE00F06E69 /* SWGCategory.m */,
EAEA85D01811D3AE00F06E69 /* SWGDate.h */,
EAEA85D11811D3AE00F06E69 /* SWGDate.m */,
EAEA85D21811D3AE00F06E69 /* SWGFile.h */,
EAEA85D31811D3AE00F06E69 /* SWGFile.m */,
EAEA85D41811D3AE00F06E69 /* SWGObject.h */,
EAEA85D51811D3AE00F06E69 /* SWGObject.m */,
EAEA85D61811D3AE00F06E69 /* SWGOrder.h */,
EAEA85D71811D3AE00F06E69 /* SWGOrder.m */,
EAEA85D81811D3AE00F06E69 /* SWGPet.h */,
EAEA85D91811D3AE00F06E69 /* SWGPet.m */,
EAEA85DA1811D3AE00F06E69 /* SWGPetApi.h */,
EAEA85DB1811D3AE00F06E69 /* SWGPetApi.m */,
EAEA85DC1811D3AE00F06E69 /* SWGStoreApi.h */,
EAEA85DD1811D3AE00F06E69 /* SWGStoreApi.m */,
EAEA85DE1811D3AE00F06E69 /* SWGTag.h */,
EAEA85DF1811D3AE00F06E69 /* SWGTag.m */,
EAEA85E01811D3AE00F06E69 /* SWGUser.h */,
EAEA85E11811D3AE00F06E69 /* SWGUser.m */,
EAEA85E21811D3AE00F06E69 /* SWGUserApi.h */,
EAEA85E31811D3AE00F06E69 /* SWGUserApi.m */,
); );
name = Tests; name = client;
path = ../client;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
/* End PBXGroup section */ /* End PBXGroup section */
/* Begin PBXNativeTarget section */ /* Begin PBXNativeTarget section */
EA07F4B816134F27006A2112 /* PetstoreClient */ = { EA6699951811D2FA00A70D03 /* PetstoreClient */ = {
isa = PBXNativeTarget; isa = PBXNativeTarget;
buildConfigurationList = EA07F4C816134F27006A2112 /* Build configuration list for PBXNativeTarget "PetstoreClient" */; buildConfigurationList = EA6699CB1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "PetstoreClient" */;
buildPhases = ( buildPhases = (
EA07F4B516134F27006A2112 /* Sources */, 04DAA264FD78471BBAD25173 /* Check Pods Manifest.lock */,
EA07F4B616134F27006A2112 /* Frameworks */, EA6699921811D2FA00A70D03 /* Sources */,
EA07F4B716134F27006A2112 /* CopyFiles */, EA6699931811D2FA00A70D03 /* Frameworks */,
EA6699941811D2FA00A70D03 /* Resources */,
3692D11BB04F489DAA7C0B6A /* Copy Pods Resources */,
); );
buildRules = ( buildRules = (
); );
@ -241,152 +253,213 @@
); );
name = PetstoreClient; name = PetstoreClient;
productName = PetstoreClient; productName = PetstoreClient;
productReference = EA07F4B916134F27006A2112 /* PetstoreClient */; productReference = EA6699961811D2FA00A70D03 /* PetstoreClient.app */;
productType = "com.apple.product-type.tool"; productType = "com.apple.product-type.application";
}; };
EA07F4F11613521A006A2112 /* PetstoreClientTests */ = { EA6699B91811D2FB00A70D03 /* PetstoreClientTests */ = {
isa = PBXNativeTarget; isa = PBXNativeTarget;
buildConfigurationList = EA07F5051613521A006A2112 /* Build configuration list for PBXNativeTarget "PetstoreClientTests" */; buildConfigurationList = EA6699CE1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "PetstoreClientTests" */;
buildPhases = ( buildPhases = (
EA07F4ED1613521A006A2112 /* Sources */, EA6699B61811D2FB00A70D03 /* Sources */,
EA07F4EE1613521A006A2112 /* Frameworks */, EA6699B71811D2FB00A70D03 /* Frameworks */,
EA07F4EF1613521A006A2112 /* Resources */, EA6699B81811D2FB00A70D03 /* Resources */,
EA07F4F01613521A006A2112 /* ShellScript */,
); );
buildRules = ( buildRules = (
); );
dependencies = ( dependencies = (
EA07F52F161357A5006A2112 /* PBXTargetDependency */, EA6699C01811D2FB00A70D03 /* PBXTargetDependency */,
); );
name = PetstoreClientTests; name = PetstoreClientTests;
productName = PetstoreClientTests; productName = PetstoreClientTests;
productReference = EA07F4F21613521A006A2112 /* PetstoreClientTests.octest */; productReference = EA6699BA1811D2FB00A70D03 /* PetstoreClientTests.xctest */;
productType = "com.apple.product-type.bundle"; productType = "com.apple.product-type.bundle.unit-test";
}; };
/* End PBXNativeTarget section */ /* End PBXNativeTarget section */
/* Begin PBXProject section */ /* Begin PBXProject section */
EA07F4B016134F27006A2112 /* Project object */ = { EA66998E1811D2FA00A70D03 /* Project object */ = {
isa = PBXProject; isa = PBXProject;
attributes = { attributes = {
LastUpgradeCheck = 0450; LastUpgradeCheck = 0500;
ORGANIZATIONNAME = "Tony Tam"; ORGANIZATIONNAME = Reverb;
TargetAttributes = {
EA6699B91811D2FB00A70D03 = {
TestTargetID = EA6699951811D2FA00A70D03;
}; };
buildConfigurationList = EA07F4B316134F27006A2112 /* Build configuration list for PBXProject "PetstoreClient" */; };
};
buildConfigurationList = EA6699911811D2FA00A70D03 /* Build configuration list for PBXProject "PetstoreClient" */;
compatibilityVersion = "Xcode 3.2"; compatibilityVersion = "Xcode 3.2";
developmentRegion = English; developmentRegion = English;
hasScannedForEncodings = 0; hasScannedForEncodings = 0;
knownRegions = ( knownRegions = (
en, en,
Base,
); );
mainGroup = EA07F4AE16134F27006A2112; mainGroup = EA66998D1811D2FA00A70D03;
productRefGroup = EA07F4BA16134F27006A2112 /* Products */; productRefGroup = EA6699971811D2FA00A70D03 /* Products */;
projectDirPath = ""; projectDirPath = "";
projectRoot = ""; projectRoot = "";
targets = ( targets = (
EA07F4B816134F27006A2112 /* PetstoreClient */, EA6699951811D2FA00A70D03 /* PetstoreClient */,
EA07F4F11613521A006A2112 /* PetstoreClientTests */, EA6699B91811D2FB00A70D03 /* PetstoreClientTests */,
); );
}; };
/* End PBXProject section */ /* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */ /* Begin PBXResourcesBuildPhase section */
EA07F4EF1613521A006A2112 /* Resources */ = { EA6699941811D2FA00A70D03 /* Resources */ = {
isa = PBXResourcesBuildPhase; isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
EA6699B01811D2FA00A70D03 /* Main_iPad.storyboard in Resources */,
EA6699B51811D2FA00A70D03 /* Images.xcassets in Resources */,
EA6699AD1811D2FA00A70D03 /* Main_iPhone.storyboard in Resources */,
EA6699A41811D2FA00A70D03 /* InfoPlist.strings in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
EA6699B81811D2FB00A70D03 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
EA6699C61811D2FB00A70D03 /* InfoPlist.strings in Resources */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
/* End PBXResourcesBuildPhase section */ /* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */
EA07F4F01613521A006A2112 /* ShellScript */ = { 04DAA264FD78471BBAD25173 /* Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
); );
inputPaths = ( inputPaths = (
); );
name = "Check Pods Manifest.lock";
outputPaths = ( outputPaths = (
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh; shellPath = /bin/sh;
shellScript = "# Run the unit tests in this test bundle.\n\"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests\"\n"; shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n";
showEnvVarsInLog = 0;
};
3692D11BB04F489DAA7C0B6A /* Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Copy Pods Resources";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/../Pods/Pods-resources.sh\"\n";
showEnvVarsInLog = 0;
}; };
/* End PBXShellScriptBuildPhase section */ /* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */
EA07F4B516134F27006A2112 /* Sources */ = { EA6699921811D2FA00A70D03 /* Sources */ = {
isa = PBXSourcesBuildPhase; isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
EA07F4C116134F27006A2112 /* main.m in Sources */, EAEA85E51811D3AE00F06E69 /* SWGCategory.m in Sources */,
EA4F4D3816F1A90A00F24B35 /* NIKFile.m in Sources */, EAEA85ED1811D3AE00F06E69 /* SWGTag.m in Sources */,
EA6699B31811D2FA00A70D03 /* ViewController.m in Sources */,
EA6699AA1811D2FA00A70D03 /* AppDelegate.m in Sources */,
EAEA85EE1811D3AE00F06E69 /* SWGUser.m in Sources */,
EAEA85EF1811D3AE00F06E69 /* SWGUserApi.m in Sources */,
EAEA85EB1811D3AE00F06E69 /* SWGPetApi.m in Sources */,
EAEA85E61811D3AE00F06E69 /* SWGDate.m in Sources */,
EA6699A61811D2FA00A70D03 /* main.m in Sources */,
EAEA85EA1811D3AE00F06E69 /* SWGPet.m in Sources */,
EAEA85E41811D3AE00F06E69 /* SWGApiClient.m in Sources */,
EAEA85EC1811D3AE00F06E69 /* SWGStoreApi.m in Sources */,
EAEA85E91811D3AE00F06E69 /* SWGOrder.m in Sources */,
EAEA85E81811D3AE00F06E69 /* SWGObject.m in Sources */,
EAEA85E71811D3AE00F06E69 /* SWGFile.m in Sources */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
EA07F4ED1613521A006A2112 /* Sources */ = { EA6699B61811D2FB00A70D03 /* Sources */ = {
isa = PBXSourcesBuildPhase; isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
EAE9043A17BF31C800486EFE /* PetApiTest.m in Sources */, EA6699C81811D2FB00A70D03 /* PetstoreClientTests.m in Sources */,
EAE9043B17BF31C800486EFE /* PetApiTest.h in Sources */,
EAE9043C17BF31C800486EFE /* UserApiTest.h in Sources */,
EAE9043D17BF31C800486EFE /* UserApiTest.m in Sources */,
EAE9043817BF318800486EFE /* NIKFile.h in Sources */,
EAE9043917BF318800486EFE /* NIKFile.m in Sources */,
EAE9042217BF2F7900486EFE /* NIKApiInvoker.h in Sources */,
EAE9042317BF2F7900486EFE /* NIKApiInvoker.m in Sources */,
EAE9042417BF2F7900486EFE /* NIKDate.h in Sources */,
EAE9042517BF2F7900486EFE /* NIKDate.m in Sources */,
EAE9042617BF2F7900486EFE /* NIKSwaggerObject.h in Sources */,
EAE9042717BF2F7900486EFE /* NIKSwaggerObject.m in Sources */,
EAE9042817BF2F7900486EFE /* RVBCategory.h in Sources */,
EAE9042917BF2F7900486EFE /* RVBCategory.m in Sources */,
EAE9042A17BF2F7900486EFE /* RVBOrder.h in Sources */,
EAE9042B17BF2F7900486EFE /* RVBOrder.m in Sources */,
EAE9042C17BF2F7900486EFE /* RVBPet.h in Sources */,
EAE9042D17BF2F7900486EFE /* RVBPet.m in Sources */,
EAE9042E17BF2F7900486EFE /* RVBPetApi.h in Sources */,
EAE9042F17BF2F7900486EFE /* RVBPetApi.m in Sources */,
EAE9043017BF2F7900486EFE /* RVBStoreApi.h in Sources */,
EAE9043117BF2F7900486EFE /* RVBStoreApi.m in Sources */,
EAE9043217BF2F7900486EFE /* RVBTag.h in Sources */,
EAE9043317BF2F7900486EFE /* RVBTag.m in Sources */,
EAE9043417BF2F7900486EFE /* RVBUser.h in Sources */,
EAE9043517BF2F7900486EFE /* RVBUser.m in Sources */,
EAE9043617BF2F7900486EFE /* RVBUserApi.h in Sources */,
EAE9043717BF2F7900486EFE /* RVBUserApi.m in Sources */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
/* End PBXSourcesBuildPhase section */ /* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */ /* Begin PBXTargetDependency section */
EA07F52F161357A5006A2112 /* PBXTargetDependency */ = { EA6699C01811D2FB00A70D03 /* PBXTargetDependency */ = {
isa = PBXTargetDependency; isa = PBXTargetDependency;
target = EA07F4B816134F27006A2112 /* PetstoreClient */; target = EA6699951811D2FA00A70D03 /* PetstoreClient */;
targetProxy = EA07F52E161357A5006A2112 /* PBXContainerItemProxy */; targetProxy = EA6699BF1811D2FB00A70D03 /* PBXContainerItemProxy */;
}; };
/* End PBXTargetDependency section */ /* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
EA6699A21811D2FA00A70D03 /* InfoPlist.strings */ = {
isa = PBXVariantGroup;
children = (
EA6699A31811D2FA00A70D03 /* en */,
);
name = InfoPlist.strings;
sourceTree = "<group>";
};
EA6699AB1811D2FA00A70D03 /* Main_iPhone.storyboard */ = {
isa = PBXVariantGroup;
children = (
EA6699AC1811D2FA00A70D03 /* Base */,
);
name = Main_iPhone.storyboard;
sourceTree = "<group>";
};
EA6699AE1811D2FA00A70D03 /* Main_iPad.storyboard */ = {
isa = PBXVariantGroup;
children = (
EA6699AF1811D2FA00A70D03 /* Base */,
);
name = Main_iPad.storyboard;
sourceTree = "<group>";
};
EA6699C41811D2FB00A70D03 /* InfoPlist.strings */ = {
isa = PBXVariantGroup;
children = (
EA6699C51811D2FB00A70D03 /* en */,
);
name = InfoPlist.strings;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */ /* Begin XCBuildConfiguration section */
EA07F4C616134F27006A2112 /* Debug */ = { EA6699C91811D2FB00A70D03 /* Debug */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO; ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_64_BIT)"; ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)";
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++"; CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
FRAMEWORK_SEARCH_PATHS = "\"$(SDKROOT)/Developer/Library/Frameworks $(DEVELOPER_LIBRARY_DIR)/Frameworks\"";
GCC_C_LANGUAGE_STANDARD = gnu99; GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO; GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_OPTIMIZATION_LEVEL = 0; GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = ( GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1", "DEBUG=1",
@ -394,122 +467,153 @@
); );
GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES; GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.8; IPHONEOS_DEPLOYMENT_TARGET = 7.0;
ONLY_ACTIVE_ARCH = YES; ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx; SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
}; };
name = Debug; name = Debug;
}; };
EA07F4C716134F27006A2112 /* Release */ = { EA6699CA1811D2FB00A70D03 /* Release */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO; ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_64_BIT)"; ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)";
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++"; CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = YES; COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO;
FRAMEWORK_SEARCH_PATHS = "\"$(SDKROOT)/Developer/Library/Frameworks $(DEVELOPER_LIBRARY_DIR)/Frameworks\"";
GCC_C_LANGUAGE_STANDARD = gnu99; GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES; GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.8; IPHONEOS_DEPLOYMENT_TARGET = 7.0;
SDKROOT = macosx; SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
}; };
name = Release; name = Release;
}; };
EA07F4C916134F27006A2112 /* Debug */ = { EA6699CC1811D2FB00A70D03 /* Debug */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
baseConfigurationReference = EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */;
buildSettings = { buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch"; GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch";
INFOPLIST_FILE = "PetstoreClient/PetstoreClient-Info.plist";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = app;
}; };
name = Debug; name = Debug;
}; };
EA07F4CA16134F27006A2112 /* Release */ = { EA6699CD1811D2FB00A70D03 /* Release */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
baseConfigurationReference = EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */;
buildSettings = { buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch"; GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch";
INFOPLIST_FILE = "PetstoreClient/PetstoreClient-Info.plist";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = app;
}; };
name = Release; name = Release;
}; };
EA07F5061613521A006A2112 /* Debug */ = { EA6699CF1811D2FB00A70D03 /* Debug */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
COMBINE_HIDPI_IMAGES = YES; ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)";
BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/PetstoreClient.app/PetstoreClient";
FRAMEWORK_SEARCH_PATHS = ( FRAMEWORK_SEARCH_PATHS = (
"$(DEVELOPER_LIBRARY_DIR)/Frameworks",
"$(DEVELOPER_LIBRARY_DIR)/Frameworks",
"$(SDKROOT)/Developer/Library/Frameworks", "$(SDKROOT)/Developer/Library/Frameworks",
"$(inherited)",
"$(DEVELOPER_FRAMEWORKS_DIR)",
); );
GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "../tests/PetstoreClientTests-Prefix.pch"; GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch";
INFOPLIST_FILE = "../tests/PetstoreClientTests-Info.plist"; GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
INFOPLIST_FILE = "PetstoreClientTests/PetstoreClientTests-Info.plist";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = octest; TEST_HOST = "$(BUNDLE_LOADER)";
WRAPPER_EXTENSION = xctest;
}; };
name = Debug; name = Debug;
}; };
EA07F5071613521A006A2112 /* Release */ = { EA6699D01811D2FB00A70D03 /* Release */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
COMBINE_HIDPI_IMAGES = YES; ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)";
BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/PetstoreClient.app/PetstoreClient";
FRAMEWORK_SEARCH_PATHS = ( FRAMEWORK_SEARCH_PATHS = (
"$(DEVELOPER_LIBRARY_DIR)/Frameworks",
"$(DEVELOPER_LIBRARY_DIR)/Frameworks",
"$(SDKROOT)/Developer/Library/Frameworks", "$(SDKROOT)/Developer/Library/Frameworks",
"$(inherited)",
"$(DEVELOPER_FRAMEWORKS_DIR)",
); );
GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "../tests/PetstoreClientTests-Prefix.pch"; GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch";
INFOPLIST_FILE = "../tests/PetstoreClientTests-Info.plist"; INFOPLIST_FILE = "PetstoreClientTests/PetstoreClientTests-Info.plist";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = octest; TEST_HOST = "$(BUNDLE_LOADER)";
WRAPPER_EXTENSION = xctest;
}; };
name = Release; name = Release;
}; };
/* End XCBuildConfiguration section */ /* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */ /* Begin XCConfigurationList section */
EA07F4B316134F27006A2112 /* Build configuration list for PBXProject "PetstoreClient" */ = { EA6699911811D2FA00A70D03 /* Build configuration list for PBXProject "PetstoreClient" */ = {
isa = XCConfigurationList; isa = XCConfigurationList;
buildConfigurations = ( buildConfigurations = (
EA07F4C616134F27006A2112 /* Debug */, EA6699C91811D2FB00A70D03 /* Debug */,
EA07F4C716134F27006A2112 /* Release */, EA6699CA1811D2FB00A70D03 /* Release */,
); );
defaultConfigurationIsVisible = 0; defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release; defaultConfigurationName = Release;
}; };
EA07F4C816134F27006A2112 /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { EA6699CB1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = {
isa = XCConfigurationList; isa = XCConfigurationList;
buildConfigurations = ( buildConfigurations = (
EA07F4C916134F27006A2112 /* Debug */, EA6699CC1811D2FB00A70D03 /* Debug */,
EA07F4CA16134F27006A2112 /* Release */, EA6699CD1811D2FB00A70D03 /* Release */,
); );
defaultConfigurationIsVisible = 0; defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release; defaultConfigurationName = Release;
}; };
EA07F5051613521A006A2112 /* Build configuration list for PBXNativeTarget "PetstoreClientTests" */ = { EA6699CE1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "PetstoreClientTests" */ = {
isa = XCConfigurationList; isa = XCConfigurationList;
buildConfigurations = ( buildConfigurations = (
EA07F5061613521A006A2112 /* Debug */, EA6699CF1811D2FB00A70D03 /* Debug */,
EA07F5071613521A006A2112 /* Release */, EA6699D01811D2FB00A70D03 /* Release */,
); );
defaultConfigurationIsVisible = 0; defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release; defaultConfigurationName = Release;
}; };
/* End XCConfigurationList section */ /* End XCConfigurationList section */
}; };
rootObject = EA07F4B016134F27006A2112 /* Project object */; rootObject = EA66998E1811D2FA00A70D03 /* Project object */;
} }

View File

@ -0,0 +1,41 @@
<?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>IDESourceControlProjectFavoriteDictionaryKey</key>
<false/>
<key>IDESourceControlProjectIdentifier</key>
<string>7A33CEA3-5D3F-4B6D-8F47-84701AB3E283</string>
<key>IDESourceControlProjectName</key>
<string>PetstoreClient</string>
<key>IDESourceControlProjectOriginsDictionary</key>
<dict>
<key>92840518-904D-4771-AA3D-9AF52CA48B71</key>
<string>ssh://github.com/wordnik/swagger-codegen.git</string>
</dict>
<key>IDESourceControlProjectPath</key>
<string>samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.xcworkspace</string>
<key>IDESourceControlProjectRelativeInstallPathDictionary</key>
<dict>
<key>92840518-904D-4771-AA3D-9AF52CA48B71</key>
<string>../../../../../../..</string>
</dict>
<key>IDESourceControlProjectURL</key>
<string>ssh://github.com/wordnik/swagger-codegen.git</string>
<key>IDESourceControlProjectVersion</key>
<integer>110</integer>
<key>IDESourceControlProjectWCCIdentifier</key>
<string>92840518-904D-4771-AA3D-9AF52CA48B71</string>
<key>IDESourceControlProjectWCConfigurations</key>
<array>
<dict>
<key>IDESourceControlRepositoryExtensionIdentifierKey</key>
<string>public.vcs.git</string>
<key>IDESourceControlWCCIdentifierKey</key>
<string>92840518-904D-4771-AA3D-9AF52CA48B71</string>
<key>IDESourceControlWCCName</key>
<string>swagger-codegen</string>
</dict>
</array>
</dict>
</plist>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
type = "1"
version = "1.0">
</Bucket>

View File

@ -1,101 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
type = "1"
version = "2.0">
<Breakpoints>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
shouldBeEnabled = "No"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "../tests/PetApiTest.m"
timestampString = "398404382.504334"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "20"
endingLineNumber = "20"
landmarkName = "-testGetPetById"
landmarkType = "5">
<Locations>
<Location
shouldBeEnabled = "No"
ignoreCount = "0"
continueAfterRunningActions = "No"
symbolName = "-[PetApiTest testGetPetById]"
moduleName = "PetstoreClientTests"
urlString = "file://localhost/Users/tony/dev/projects/fehguy/swagger-codegen/samples/client/petstore/objc/tests/PetApiTest.m"
timestampString = "398406089.256685"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "20"
endingLineNumber = "20"
offsetFromSymbolStart = "52">
</Location>
<Location
shouldBeEnabled = "No"
ignoreCount = "0"
continueAfterRunningActions = "No"
symbolName = "__28-[PetApiTest testGetPetById]_block_invoke"
moduleName = "PetstoreClientTests"
urlString = "file://localhost/Users/tony/dev/projects/fehguy/swagger-codegen/samples/client/petstore/objc/tests/PetApiTest.m"
timestampString = "398406089.257244"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "20"
endingLineNumber = "20"
offsetFromSymbolStart = "67">
</Location>
</Locations>
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
shouldBeEnabled = "No"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "../client/NIKApiInvoker.m"
timestampString = "398404435.909212"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "146"
endingLineNumber = "146"
landmarkName = "-dictionary:method:queryParams:body:headerParams:contentType:completionBlock:"
landmarkType = "5">
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
shouldBeEnabled = "No"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "../client/NIKApiInvoker.m"
timestampString = "398404448.364827"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "165"
endingLineNumber = "165"
landmarkName = "-dictionary:method:queryParams:body:headerParams:contentType:completionBlock:"
landmarkType = "5">
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
shouldBeEnabled = "No"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "../tests/PetApiTest.m"
timestampString = "398405359.218379"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "16"
endingLineNumber = "16"
landmarkName = "-testGetPetById"
landmarkType = "5">
</BreakpointContent>
</BreakpointProxy>
</Breakpoints>
</Bucket>

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<Scheme <Scheme
LastUpgradeVersion = "0450" LastUpgradeVersion = "0500"
version = "1.3"> version = "1.3">
<BuildAction <BuildAction
parallelizeBuildables = "YES" parallelizeBuildables = "YES"
@ -14,8 +14,8 @@
buildForAnalyzing = "YES"> buildForAnalyzing = "YES">
<BuildableReference <BuildableReference
BuildableIdentifier = "primary" BuildableIdentifier = "primary"
BlueprintIdentifier = "EA07F4B816134F27006A2112" BlueprintIdentifier = "EA6699951811D2FA00A70D03"
BuildableName = "PetstoreClient" BuildableName = "PetstoreClient.app"
BlueprintName = "PetstoreClient" BlueprintName = "PetstoreClient"
ReferencedContainer = "container:PetstoreClient.xcodeproj"> ReferencedContainer = "container:PetstoreClient.xcodeproj">
</BuildableReference> </BuildableReference>
@ -28,12 +28,22 @@
shouldUseLaunchSchemeArgsEnv = "YES" shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug"> buildConfiguration = "Debug">
<Testables> <Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "EA6699B91811D2FB00A70D03"
BuildableName = "PetstoreClientTests.xctest"
BlueprintName = "PetstoreClientTests"
ReferencedContainer = "container:PetstoreClient.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables> </Testables>
<MacroExpansion> <MacroExpansion>
<BuildableReference <BuildableReference
BuildableIdentifier = "primary" BuildableIdentifier = "primary"
BlueprintIdentifier = "EA07F4B816134F27006A2112" BlueprintIdentifier = "EA6699951811D2FA00A70D03"
BuildableName = "PetstoreClient" BuildableName = "PetstoreClient.app"
BlueprintName = "PetstoreClient" BlueprintName = "PetstoreClient"
ReferencedContainer = "container:PetstoreClient.xcodeproj"> ReferencedContainer = "container:PetstoreClient.xcodeproj">
</BuildableReference> </BuildableReference>
@ -51,8 +61,8 @@
<BuildableProductRunnable> <BuildableProductRunnable>
<BuildableReference <BuildableReference
BuildableIdentifier = "primary" BuildableIdentifier = "primary"
BlueprintIdentifier = "EA07F4B816134F27006A2112" BlueprintIdentifier = "EA6699951811D2FA00A70D03"
BuildableName = "PetstoreClient" BuildableName = "PetstoreClient.app"
BlueprintName = "PetstoreClient" BlueprintName = "PetstoreClient"
ReferencedContainer = "container:PetstoreClient.xcodeproj"> ReferencedContainer = "container:PetstoreClient.xcodeproj">
</BuildableReference> </BuildableReference>
@ -69,8 +79,8 @@
<BuildableProductRunnable> <BuildableProductRunnable>
<BuildableReference <BuildableReference
BuildableIdentifier = "primary" BuildableIdentifier = "primary"
BlueprintIdentifier = "EA07F4B816134F27006A2112" BlueprintIdentifier = "EA6699951811D2FA00A70D03"
BuildableName = "PetstoreClient" BuildableName = "PetstoreClient.app"
BlueprintName = "PetstoreClient" BlueprintName = "PetstoreClient"
ReferencedContainer = "container:PetstoreClient.xcodeproj"> ReferencedContainer = "container:PetstoreClient.xcodeproj">
</BuildableReference> </BuildableReference>

View File

@ -9,20 +9,15 @@
<key>orderHint</key> <key>orderHint</key>
<integer>0</integer> <integer>0</integer>
</dict> </dict>
<key>PetstoreClientTests.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>1</integer>
</dict>
</dict> </dict>
<key>SuppressBuildableAutocreation</key> <key>SuppressBuildableAutocreation</key>
<dict> <dict>
<key>EA07F4B816134F27006A2112</key> <key>EA6699951811D2FA00A70D03</key>
<dict> <dict>
<key>primary</key> <key>primary</key>
<true/> <true/>
</dict> </dict>
<key>EA07F4F11613521A006A2112</key> <key>EA6699B91811D2FB00A70D03</key>
<dict> <dict>
<key>primary</key> <key>primary</key>
<true/> <true/>

View File

@ -0,0 +1,15 @@
//
// AppDelegate.h
// PetstoreClient
//
// Created by Tony Tam on 10/18/13.
// Copyright (c) 2013 Reverb. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end

View File

@ -0,0 +1,46 @@
//
// AppDelegate.m
// PetstoreClient
//
// Created by Tony Tam on 10/18/13.
// Copyright (c) 2013 Reverb. All rights reserved.
//
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="4451" systemVersion="13A461" targetRuntime="iOS.CocoaTouch.iPad" propertyAccessControl="none" useAutolayout="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="3676"/>
</dependencies>
<scenes>
<!--class Prefix:identifier View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="20" width="768" height="1004"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
<simulatedMetricsContainer key="defaultSimulatedMetrics">
<simulatedStatusBarMetrics key="statusBar" statusBarStyle="blackOpaque"/>
<simulatedOrientationMetrics key="orientation"/>
<simulatedScreenMetrics key="destination"/>
</simulatedMetricsContainer>
</document>

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="4451" systemVersion="13A461" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" initialViewController="vXZ-lx-hvc">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="3676"/>
</dependencies>
<scenes>
<!--class Prefix:identifier View Controller-->
<scene sceneID="ufC-wZ-h7g">
<objects>
<viewController id="vXZ-lx-hvc" customClass="ViewController" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="kh9-bI-dsS">
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="x5A-6p-PRh" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
<simulatedMetricsContainer key="defaultSimulatedMetrics">
<simulatedStatusBarMetrics key="statusBar"/>
<simulatedOrientationMetrics key="orientation"/>
<simulatedScreenMetrics key="destination" type="retina4"/>
</simulatedMetricsContainer>
</document>

View File

@ -0,0 +1,53 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}

View File

@ -0,0 +1,51 @@
{
"images" : [
{
"orientation" : "portrait",
"idiom" : "iphone",
"extent" : "full-screen",
"minimum-system-version" : "7.0",
"scale" : "2x"
},
{
"orientation" : "portrait",
"idiom" : "iphone",
"subtype" : "retina4",
"extent" : "full-screen",
"minimum-system-version" : "7.0",
"scale" : "2x"
},
{
"orientation" : "portrait",
"idiom" : "ipad",
"extent" : "full-screen",
"minimum-system-version" : "7.0",
"scale" : "1x"
},
{
"orientation" : "landscape",
"idiom" : "ipad",
"extent" : "full-screen",
"minimum-system-version" : "7.0",
"scale" : "1x"
},
{
"orientation" : "portrait",
"idiom" : "ipad",
"extent" : "full-screen",
"minimum-system-version" : "7.0",
"scale" : "2x"
},
{
"orientation" : "landscape",
"idiom" : "ipad",
"extent" : "full-screen",
"minimum-system-version" : "7.0",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}

View File

@ -0,0 +1,49 @@
<?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>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>com.reverb.${PRODUCT_NAME:rfc1034identifier}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIMainStoryboardFile</key>
<string>Main_iPhone</string>
<key>UIMainStoryboardFile~ipad</key>
<string>Main_iPad</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>

View File

@ -1,7 +1,17 @@
// //
// Prefix header for all source files of the 'PetstoreClient' target in the 'PetstoreClient' project // Prefix header
//
// The contents of this file are implicitly included at the beginning of every source file.
// //
#ifdef __OBJC__ #import <Availability.h>
#import <Foundation/Foundation.h>
#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#endif #endif

View File

@ -1,79 +0,0 @@
.\"Modified from man(1) of FreeBSD, the NetBSD mdoc.template, and mdoc.samples.
.\"See Also:
.\"man mdoc.samples for a complete listing of options
.\"man mdoc for the short list of editing options
.\"/usr/share/misc/mdoc.template
.Dd 9/26/12 \" DATE
.Dt PetstoreClient 1 \" Program name and manual section number
.Os Darwin
.Sh NAME \" Section Header - required - don't modify
.Nm PetstoreClient,
.\" The following lines are read in generating the apropos(man -k) database. Use only key
.\" words here as the database is built based on the words here and in the .ND line.
.Nm Other_name_for_same_program(),
.Nm Yet another name for the same program.
.\" Use .Nm macro to designate other names for the documented program.
.Nd This line parsed for whatis database.
.Sh SYNOPSIS \" Section Header - required - don't modify
.Nm
.Op Fl abcd \" [-abcd]
.Op Fl a Ar path \" [-a path]
.Op Ar file \" [file]
.Op Ar \" [file ...]
.Ar arg0 \" Underlined argument - use .Ar anywhere to underline
arg2 ... \" Arguments
.Sh DESCRIPTION \" Section Header - required - don't modify
Use the .Nm macro to refer to your program throughout the man page like such:
.Nm
Underlining is accomplished with the .Ar macro like this:
.Ar underlined text .
.Pp \" Inserts a space
A list of items with descriptions:
.Bl -tag -width -indent \" Begins a tagged list
.It item a \" Each item preceded by .It macro
Description of item a
.It item b
Description of item b
.El \" Ends the list
.Pp
A list of flags and their descriptions:
.Bl -tag -width -indent \" Differs from above in tag removed
.It Fl a \"-a flag as a list item
Description of -a flag
.It Fl b
Description of -b flag
.El \" Ends the list
.Pp
.\" .Sh ENVIRONMENT \" May not be needed
.\" .Bl -tag -width "ENV_VAR_1" -indent \" ENV_VAR_1 is width of the string ENV_VAR_1
.\" .It Ev ENV_VAR_1
.\" Description of ENV_VAR_1
.\" .It Ev ENV_VAR_2
.\" Description of ENV_VAR_2
.\" .El
.Sh FILES \" File used or created by the topic of the man page
.Bl -tag -width "/Users/joeuser/Library/really_long_file_name" -compact
.It Pa /usr/share/file_name
FILE_1 description
.It Pa /Users/joeuser/Library/really_long_file_name
FILE_2 description
.El \" Ends the list
.\" .Sh DIAGNOSTICS \" May not be needed
.\" .Bl -diag
.\" .It Diagnostic Tag
.\" Diagnostic informtion here.
.\" .It Diagnostic Tag
.\" Diagnostic informtion here.
.\" .El
.Sh SEE ALSO
.\" List links in ascending order by section, alphabetically within a section.
.\" Please do not reference files that do not exist without filing a bug report
.Xr a 1 ,
.Xr b 1 ,
.Xr c 1 ,
.Xr a 2 ,
.Xr b 2 ,
.Xr a 3 ,
.Xr b 3
.\" .Sh BUGS \" Document known, unremedied bugs
.\" .Sh HISTORY \" Document history if command behaves in a unique manner

View File

@ -0,0 +1,13 @@
//
// ViewController.h
// PetstoreClient
//
// Created by Tony Tam on 10/18/13.
// Copyright (c) 2013 Reverb. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end

View File

@ -0,0 +1,36 @@
//
// ViewController.m
// PetstoreClient
//
// Created by Tony Tam on 10/18/13.
// Copyright (c) 2013 Reverb. All rights reserved.
//
#import "ViewController.h"
#import "SWGPetApi.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
SWGPetApi * api = [[SWGPetApi alloc] init];
[api getPetByIdWithCompletionBlock:@10 completionHandler:^(SWGPet *output, NSError *error) {
NSLog(@"%@", [output asDictionary]);
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end

View File

@ -0,0 +1,2 @@
/* Localized versions of Info.plist keys */

View File

@ -2,21 +2,17 @@
// main.m // main.m
// PetstoreClient // PetstoreClient
// //
// Created by Tony Tam on 9/26/12. // Created by Tony Tam on 10/18/13.
// Copyright (c) 2012 Tony Tam. All rights reserved. // Copyright (c) 2013 Reverb. All rights reserved.
// //
#import <Foundation/Foundation.h> #import <UIKit/UIKit.h>
int main(int argc, const char * argv[]) #import "AppDelegate.h"
int main(int argc, char * argv[])
{ {
@autoreleasepool { @autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
// insert code here...
NSLog(@"Hello, World!");
} }
return 0;
} }

View File

@ -0,0 +1,22 @@
<?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>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>com.reverb.${PRODUCT_NAME:rfc1034identifier}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>

View File

@ -0,0 +1,34 @@
//
// PetstoreClientTests.m
// PetstoreClientTests
//
// Created by Tony Tam on 10/18/13.
// Copyright (c) 2013 Reverb. All rights reserved.
//
#import <XCTest/XCTest.h>
@interface PetstoreClientTests : XCTestCase
@end
@implementation PetstoreClientTests
- (void)setUp
{
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
}
- (void)tearDown
{
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
}
- (void)testExample
{
XCTFail(@"No implementation for \"%s\"", __PRETTY_FUNCTION__);
}
@end

View File

@ -0,0 +1,2 @@
/* Localized versions of Info.plist keys */

View File

@ -0,0 +1,4 @@
platform :ios, '6.0'
xcodeproj 'PetstoreClient/PetstoreClient.xcodeproj'
pod 'AFNetworking', '~> 1.0'

View File

@ -0,0 +1,10 @@
PODS:
- AFNetworking (1.3.3)
DEPENDENCIES:
- AFNetworking (~> 1.0)
SPEC CHECKSUMS:
AFNetworking: 0700ec7a58c36ad217173e167f6e4df7270df66b
COCOAPODS: 0.25.0

View File

@ -0,0 +1,641 @@
// AFHTTPClient.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFURLConnectionOperation.h"
#import <Availability.h>
/**
`AFHTTPClient` captures the common patterns of communicating with an web application over HTTP. It encapsulates information like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations.
## Automatic Content Parsing
Instances of `AFHTTPClient` may specify which types of requests it expects and should handle by registering HTTP operation classes for automatic parsing. Registered classes will determine whether they can handle a particular request, and then construct a request operation accordingly in `enqueueHTTPRequestOperationWithRequest:success:failure`.
## Subclassing Notes
In most cases, one should create an `AFHTTPClient` subclass for each website or web application that your application communicates with. It is often useful, also, to define a class method that returns a singleton shared HTTP client in each subclass, that persists authentication credentials and other configuration across the entire application.
## Methods to Override
To change the behavior of all url request construction for an `AFHTTPClient` subclass, override `requestWithMethod:path:parameters`.
To change the behavior of all request operation construction for an `AFHTTPClient` subclass, override `HTTPRequestOperationWithRequest:success:failure`.
## Default Headers
By default, `AFHTTPClient` sets the following HTTP headers:
- `Accept-Language: (comma-delimited preferred languages), en-us;q=0.8`
- `User-Agent: (generated user agent)`
You can override these HTTP headers or define new ones using `setDefaultHeader:value:`.
## URL Construction Using Relative Paths
Both `-requestWithMethod:path:parameters:` and `-multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:` construct URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`. Below are a few examples of how `baseURL` and relative paths interact:
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
[NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
[NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
[NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
[NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
[NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
[NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
Also important to note is that a trailing slash will be added to any `baseURL` without one, which would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
## NSCoding / NSCopying Conformance
`AFHTTPClient` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however:
- Archives and copies of HTTP clients will be initialized with an empty operation queue.
- NSCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.
*/
#ifdef _SYSTEMCONFIGURATION_H
typedef enum {
AFNetworkReachabilityStatusUnknown = -1,
AFNetworkReachabilityStatusNotReachable = 0,
AFNetworkReachabilityStatusReachableViaWWAN = 1,
AFNetworkReachabilityStatusReachableViaWiFi = 2,
} AFNetworkReachabilityStatus;
#else
#pragma message("SystemConfiguration framework not found in project, or not included in precompiled header. Network reachability functionality will not be available.")
#endif
#ifndef __UTTYPE__
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#pragma message("MobileCoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.")
#else
#pragma message("CoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.")
#endif
#endif
typedef enum {
AFFormURLParameterEncoding,
AFJSONParameterEncoding,
AFPropertyListParameterEncoding,
} AFHTTPClientParameterEncoding;
@class AFHTTPRequestOperation;
@protocol AFMultipartFormData;
@interface AFHTTPClient : NSObject <NSCoding, NSCopying>
///---------------------------------------
/// @name Accessing HTTP Client Properties
///---------------------------------------
/**
The url used as the base for paths specified in methods such as `getPath:parameters:success:failure`
*/
@property (readonly, nonatomic, strong) NSURL *baseURL;
/**
The string encoding used in constructing url requests. This is `NSUTF8StringEncoding` by default.
*/
@property (nonatomic, assign) NSStringEncoding stringEncoding;
/**
The `AFHTTPClientParameterEncoding` value corresponding to how parameters are encoded into a request body for request methods other than `GET`, `HEAD` or `DELETE`. This is `AFFormURLParameterEncoding` by default.
@warning Some nested parameter structures, such as a keyed array of hashes containing inconsistent keys (i.e. `@{@"": @[@{@"a" : @(1)}, @{@"b" : @(2)}]}`), cannot be unambiguously represented in query strings. It is strongly recommended that an unambiguous encoding, such as `AFJSONParameterEncoding`, is used when posting complicated or nondeterministic parameter structures.
*/
@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding;
/**
The operation queue which manages operations enqueued by the HTTP client.
*/
@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
/**
The reachability status from the device to the current `baseURL` of the `AFHTTPClient`.
@warning This property requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
*/
#ifdef _SYSTEMCONFIGURATION_H
@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
#endif
/**
Default SSL pinning mode for each `AFHTTPRequestOperation` created by `HTTPRequestOperationWithRequest:success:failure:`.
*/
@property (nonatomic, assign) AFURLConnectionOperationSSLPinningMode defaultSSLPinningMode;
/**
Whether each `AFHTTPRequestOperation` created by `HTTPRequestOperationWithRequest:success:failure:` should accept an invalid SSL certificate.
If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is set, this property defaults to `YES` for backwards compatibility. Otherwise, this property defaults to `NO`.
*/
@property (nonatomic, assign) BOOL allowsInvalidSSLCertificate;
///---------------------------------------------
/// @name Creating and Initializing HTTP Clients
///---------------------------------------------
/**
Creates and initializes an `AFHTTPClient` object with the specified base URL.
@param url The base URL for the HTTP client. This argument must not be `nil`.
@return The newly-initialized HTTP client
*/
+ (instancetype)clientWithBaseURL:(NSURL *)url;
/**
Initializes an `AFHTTPClient` object with the specified base URL.
This is the designated initializer.
@param url The base URL for the HTTP client. This argument must not be `nil`.
@return The newly-initialized HTTP client
*/
- (id)initWithBaseURL:(NSURL *)url;
///-----------------------------------
/// @name Managing Reachability Status
///-----------------------------------
/**
Sets a callback to be executed when the network availability of the `baseURL` host changes.
@param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
@warning This method requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
*/
#ifdef _SYSTEMCONFIGURATION_H
- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block;
#endif
///-------------------------------
/// @name Managing HTTP Operations
///-------------------------------
/**
Attempts to register a subclass of `AFHTTPRequestOperation`, adding it to a chain to automatically generate request operations from a URL request.
When `enqueueHTTPRequestOperationWithRequest:success:failure` is invoked, each registered class is consulted in turn to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to create an operation using `initWithURLRequest:` and do `setCompletionBlockWithSuccess:failure:`. There is no guarantee that all registered classes will be consulted. Classes are consulted in the reverse order of their registration. Attempting to register an already-registered class will move it to the top of the list.
@param operationClass The subclass of `AFHTTPRequestOperation` to register
@return `YES` if the registration is successful, `NO` otherwise. The only failure condition is if `operationClass` is not a subclass of `AFHTTPRequestOperation`.
*/
- (BOOL)registerHTTPOperationClass:(Class)operationClass;
/**
Unregisters the specified subclass of `AFHTTPRequestOperation` from the chain of classes consulted when `-requestWithMethod:path:parameters` is called.
@param operationClass The subclass of `AFHTTPRequestOperation` to register
*/
- (void)unregisterHTTPOperationClass:(Class)operationClass;
///----------------------------------
/// @name Managing HTTP Header Values
///----------------------------------
/**
Returns the value for the HTTP headers set in request objects created by the HTTP client.
@param header The HTTP header to return the default value for
@return The default value for the HTTP header, or `nil` if unspecified
*/
- (NSString *)defaultValueForHeader:(NSString *)header;
/**
Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
@param header The HTTP header to set a default value for
@param value The value set as default for the specified header, or `nil
*/
- (void)setDefaultHeader:(NSString *)header
value:(NSString *)value;
/**
Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.
@param username The HTTP basic auth username
@param password The HTTP basic auth password
*/
- (void)setAuthorizationHeaderWithUsername:(NSString *)username
password:(NSString *)password;
/**
Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a token-based authentication value, such as an OAuth access token. This overwrites any existing value for this header.
@param token The authentication token
*/
- (void)setAuthorizationHeaderWithToken:(NSString *)token;
/**
Clears any existing value for the "Authorization" HTTP header.
*/
- (void)clearAuthorizationHeader;
///-------------------------------
/// @name Managing URL Credentials
///-------------------------------
/**
Set the default URL credential to be set for request operations.
@param credential The URL credential
*/
- (void)setDefaultCredential:(NSURLCredential *)credential;
///-------------------------------
/// @name Creating Request Objects
///-------------------------------
/**
Creates an `NSMutableURLRequest` object with the specified HTTP method and path.
If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
@param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
@param path The path to be appended to the HTTP client's base URL and used as the request URL. If `nil`, no path will be appended to the base URL.
@param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
@return An `NSMutableURLRequest` object
*/
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
path:(NSString *)path
parameters:(NSDictionary *)parameters;
/**
Creates an `NSMutableURLRequest` object with the specified HTTP method and path, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream.
@param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
@param parameters The parameters to be encoded and set in the request HTTP body.
@param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. This can be used to upload files, encode HTTP body as JSON or XML, or specify multiple values for the same parameter, as one might for array values.
@return An `NSMutableURLRequest` object
*/
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
path:(NSString *)path
parameters:(NSDictionary *)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block;
///-------------------------------
/// @name Creating HTTP Operations
///-------------------------------
/**
Creates an `AFHTTPRequestOperation`.
In order to determine what kind of operation is created, each registered subclass conforming to the `AFHTTPClient` protocol is consulted (in reverse order of when they were specified) to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to generate an operation using `HTTPRequestOperationWithRequest:success:failure:`.
@param urlRequest The request object to be loaded asynchronously during execution of the operation.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
*/
- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
///----------------------------------------
/// @name Managing Enqueued HTTP Operations
///----------------------------------------
/**
Enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue.
@param operation The HTTP request operation to be enqueued.
*/
- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation;
/**
Cancels all operations in the HTTP client's operation queue whose URLs match the specified HTTP method and path.
This method only cancels `AFHTTPRequestOperations` whose request URL matches the HTTP client base URL with the path appended. For complete control over the lifecycle of enqueued operations, you can access the `operationQueue` property directly, which allows you to, for instance, cancel operations filtered by a predicate, or simply use `-cancelAllRequests`. Note that the operation queue may include non-HTTP operations, so be sure to check the type before attempting to directly introspect an operation's `request` property.
@param method The HTTP method to match for the cancelled requests, such as `GET`, `POST`, `PUT`, or `DELETE`. If `nil`, all request operations with URLs matching the path will be cancelled.
@param path The path appended to the HTTP client base URL to match against the cancelled requests. If `nil`, no path will be appended to the base URL.
*/
- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path;
///---------------------------------------
/// @name Batching HTTP Request Operations
///---------------------------------------
/**
Creates and enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue for each specified request object into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
Operations are created by passing the specified `NSURLRequest` objects in `requests`, using `-HTTPRequestOperationWithRequest:success:failure:`, with `nil` for both the `success` and `failure` parameters.
@param urlRequests The `NSURLRequest` objects used to create and enqueue operations.
@param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
@param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
*/
- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock;
/**
Enqueues the specified request operations into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
@param operations The request operations used to be batched and enqueued.
@param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
@param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
*/
- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock;
///---------------------------
/// @name Making HTTP Requests
///---------------------------
/**
Creates an `AFHTTPRequestOperation` with a `GET` request, and enqueues it to the HTTP client's operation queue.
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
@param parameters The parameters to be encoded and appended as the query string for the request URL.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)getPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates an `AFHTTPRequestOperation` with a `POST` request, and enqueues it to the HTTP client's operation queue.
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
@param parameters The parameters to be encoded and set in the request HTTP body.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)postPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates an `AFHTTPRequestOperation` with a `PUT` request, and enqueues it to the HTTP client's operation queue.
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
@param parameters The parameters to be encoded and set in the request HTTP body.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)putPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates an `AFHTTPRequestOperation` with a `DELETE` request, and enqueues it to the HTTP client's operation queue.
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
@param parameters The parameters to be encoded and appended as the query string for the request URL.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)deletePath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates an `AFHTTPRequestOperation` with a `PATCH` request, and enqueues it to the HTTP client's operation queue.
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
@param parameters The parameters to be encoded and set in the request HTTP body.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)patchPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
@end
///----------------
/// @name Constants
///----------------
/**
## Network Reachability
The following constants are provided by `AFHTTPClient` as possible network reachability statuses.
enum {
AFNetworkReachabilityStatusUnknown,
AFNetworkReachabilityStatusNotReachable,
AFNetworkReachabilityStatusReachableViaWWAN,
AFNetworkReachabilityStatusReachableViaWiFi,
}
`AFNetworkReachabilityStatusUnknown`
The `baseURL` host reachability is not known.
`AFNetworkReachabilityStatusNotReachable`
The `baseURL` host cannot be reached.
`AFNetworkReachabilityStatusReachableViaWWAN`
The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
`AFNetworkReachabilityStatusReachableViaWiFi`
The `baseURL` host can be reached via a Wi-Fi connection.
### Keys for Notification UserInfo Dictionary
Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
`AFNetworkingReachabilityNotificationStatusItem`
A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
## Parameter Encoding
The following constants are provided by `AFHTTPClient` as possible methods for serializing parameters into query string or message body values.
enum {
AFFormURLParameterEncoding,
AFJSONParameterEncoding,
AFPropertyListParameterEncoding,
}
`AFFormURLParameterEncoding`
Parameters are encoded into field/key pairs in the URL query string for `GET` `HEAD` and `DELETE` requests, and in the message body otherwise. Dictionary keys are sorted with the `caseInsensitiveCompare:` selector of their description, in order to mitigate the possibility of ambiguous query strings being generated non-deterministically. See the warning for the `parameterEncoding` property for additional information.
`AFJSONParameterEncoding`
Parameters are encoded into JSON in the message body.
`AFPropertyListParameterEncoding`
Parameters are encoded into a property list in the message body.
*/
///----------------
/// @name Functions
///----------------
/**
Returns a query string constructed by a set of parameters, using the specified encoding.
Query strings are constructed by collecting each key-value pair, percent escaping a string representation of the key-value pair, and then joining the pairs with "&".
If a query string pair has a an `NSArray` for its value, each member of the array will be represented in the format `field[]=value1&field[]value2`. Otherwise, the pair will be formatted as "field=value". String representations of both keys and values are derived using the `-description` method. The constructed query string does not include the ? character used to delimit the query component.
@param parameters The parameters used to construct the query string
@param encoding The encoding to use in constructing the query string. If you are uncertain of the correct encoding, you should use UTF-8 (`NSUTF8StringEncoding`), which is the encoding designated by RFC 3986 as the correct encoding for use in URLs.
@return A percent-escaped query string
*/
extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding encoding);
///--------------------
/// @name Notifications
///--------------------
/**
Posted when network reachability changes.
This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
@warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
*/
#ifdef _SYSTEMCONFIGURATION_H
extern NSString * const AFNetworkingReachabilityDidChangeNotification;
extern NSString * const AFNetworkingReachabilityNotificationStatusItem;
#endif
#pragma mark -
extern NSUInteger const kAFUploadStream3GSuggestedPacketSize;
extern NSTimeInterval const kAFUploadStream3GSuggestedDelay;
/**
The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPClient -multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`.
*/
@protocol AFMultipartFormData
/**
Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary.
The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively.
@param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
@param error If an error occurs, upon return contains an `NSError` object that describes the problem.
@return `YES` if the file data was successfully appended, otherwise `NO`.
*/
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
name:(NSString *)name
error:(NSError * __autoreleasing *)error;
/**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
@param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
@param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
@param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
@param error If an error occurs, upon return contains an `NSError` object that describes the problem.
@return `YES` if the file data was successfully appended otherwise `NO`.
*/
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
name:(NSString *)name
fileName:(NSString *)fileName
mimeType:(NSString *)mimeType
error:(NSError * __autoreleasing *)error;
/**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary.
@param inputStream The input stream to be appended to the form data
@param name The name to be associated with the specified input stream. This parameter must not be `nil`.
@param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
@param length The length of the specified input stream in bytes.
@param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
*/
- (void)appendPartWithInputStream:(NSInputStream *)inputStream
name:(NSString *)name
fileName:(NSString *)fileName
length:(unsigned long long)length
mimeType:(NSString *)mimeType;
/**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
@param data The data to be encoded and appended to the form data.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
@param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
@param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
*/
- (void)appendPartWithFileData:(NSData *)data
name:(NSString *)name
fileName:(NSString *)fileName
mimeType:(NSString *)mimeType;
/**
Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
@param data The data to be encoded and appended to the form data.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
*/
- (void)appendPartWithFormData:(NSData *)data
name:(NSString *)name;
/**
Appends HTTP headers, followed by the encoded data and the multipart form boundary.
@param headers The HTTP headers to be appended to the form data.
@param body The data to be encoded and appended to the form data.
*/
- (void)appendPartWithHeaders:(NSDictionary *)headers
body:(NSData *)body;
/**
Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, as of iOS 6, there is no definite way to distinguish between a 3G, EDGE, or LTE connection. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
@param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 32kb.
@param delay Duration of delay each time a packet is read. By default, no delay is set.
*/
- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
delay:(NSTimeInterval)delay;
@end

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,133 @@
// AFHTTPRequestOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFURLConnectionOperation.h"
/**
`AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
*/
@interface AFHTTPRequestOperation : AFURLConnectionOperation
///----------------------------------------------
/// @name Getting HTTP URL Connection Information
///----------------------------------------------
/**
The last HTTP response received by the operation's connection.
*/
@property (readonly, nonatomic, strong) NSHTTPURLResponse *response;
///----------------------------------------------------------
/// @name Managing And Checking For Acceptable HTTP Responses
///----------------------------------------------------------
/**
A Boolean value that corresponds to whether the status code of the response is within the specified set of acceptable status codes. Returns `YES` if `acceptableStatusCodes` is `nil`.
*/
@property (nonatomic, readonly) BOOL hasAcceptableStatusCode;
/**
A Boolean value that corresponds to whether the MIME type of the response is among the specified set of acceptable content types. Returns `YES` if `acceptableContentTypes` is `nil`.
*/
@property (nonatomic, readonly) BOOL hasAcceptableContentType;
/**
The callback dispatch queue on success. If `NULL` (default), the main queue is used.
*/
@property (nonatomic, assign) dispatch_queue_t successCallbackQueue;
/**
The callback dispatch queue on failure. If `NULL` (default), the main queue is used.
*/
@property (nonatomic, assign) dispatch_queue_t failureCallbackQueue;
///------------------------------------------------------------
/// @name Managing Acceptable HTTP Status Codes & Content Types
///------------------------------------------------------------
/**
Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
By default, this is the range 200 to 299, inclusive.
*/
+ (NSIndexSet *)acceptableStatusCodes;
/**
Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendants.
@param statusCodes The status codes to be added to the set of acceptable HTTP status codes
*/
+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes;
/**
Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
By default, this is `nil`.
*/
+ (NSSet *)acceptableContentTypes;
/**
Adds content types to the set of acceptable MIME types returned by `+acceptableContentTypes` in subsequent calls by this class and its descendants.
@param contentTypes The content types to be added to the set of acceptable MIME types
*/
+ (void)addAcceptableContentTypes:(NSSet *)contentTypes;
///-----------------------------------------------------
/// @name Determining Whether A Request Can Be Processed
///-----------------------------------------------------
/**
A Boolean value determining whether or not the class can process the specified request. For example, `AFJSONRequestOperation` may check to make sure the content type was `application/json` or the URL path extension was `.json`.
@param urlRequest The request that is determined to be supported or not supported for this class.
*/
+ (BOOL)canProcessRequest:(NSURLRequest *)urlRequest;
///-----------------------------------------------------------
/// @name Setting Completion Block Success / Failure Callbacks
///-----------------------------------------------------------
/**
Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed.
This method should be overridden in subclasses in order to specify the response object passed into the success block.
@param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request.
@param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request.
*/
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
@end
///----------------
/// @name Functions
///----------------
/**
Returns a set of MIME types detected in an HTTP `Accept` or `Content-Type` header.
*/
extern NSSet * AFContentTypesFromHTTPHeader(NSString *string);

View File

@ -0,0 +1,327 @@
// AFHTTPRequestOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFHTTPRequestOperation.h"
#import <objc/runtime.h>
// Workaround for change in imp_implementationWithBlock() with Xcode 4.5
#if defined(__IPHONE_6_0) || defined(__MAC_10_8)
#define AF_CAST_TO_BLOCK id
#else
#define AF_CAST_TO_BLOCK __bridge void *
#endif
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wstrict-selector-match"
NSSet * AFContentTypesFromHTTPHeader(NSString *string) {
if (!string) {
return nil;
}
NSArray *mediaRanges = [string componentsSeparatedByString:@","];
NSMutableSet *mutableContentTypes = [NSMutableSet setWithCapacity:mediaRanges.count];
[mediaRanges enumerateObjectsUsingBlock:^(NSString *mediaRange, __unused NSUInteger idx, __unused BOOL *stop) {
NSRange parametersRange = [mediaRange rangeOfString:@";"];
if (parametersRange.location != NSNotFound) {
mediaRange = [mediaRange substringToIndex:parametersRange.location];
}
mediaRange = [mediaRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (mediaRange.length > 0) {
[mutableContentTypes addObject:mediaRange];
}
}];
return [NSSet setWithSet:mutableContentTypes];
}
static void AFGetMediaTypeAndSubtypeWithString(NSString *string, NSString **type, NSString **subtype) {
if (!string) {
return;
}
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner setCharactersToBeSkipped:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[scanner scanUpToString:@"/" intoString:type];
[scanner scanString:@"/" intoString:nil];
[scanner scanUpToString:@";" intoString:subtype];
}
static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
NSMutableString *string = [NSMutableString string];
NSRange range = NSMakeRange([indexSet firstIndex], 1);
while (range.location != NSNotFound) {
NSUInteger nextIndex = [indexSet indexGreaterThanIndex:range.location];
while (nextIndex == range.location + range.length) {
range.length++;
nextIndex = [indexSet indexGreaterThanIndex:nextIndex];
}
if (string.length) {
[string appendString:@","];
}
if (range.length == 1) {
[string appendFormat:@"%lu", (long)range.location];
} else {
NSUInteger firstIndex = range.location;
NSUInteger lastIndex = firstIndex + range.length - 1;
[string appendFormat:@"%lu-%lu", (long)firstIndex, (long)lastIndex];
}
range.location = nextIndex;
range.length = 1;
}
return string;
}
static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL selector, id block) {
Method originalMethod = class_getClassMethod(klass, selector);
IMP implementation = imp_implementationWithBlock((AF_CAST_TO_BLOCK)block);
class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) UTF8String]), selector, implementation, method_getTypeEncoding(originalMethod));
}
#pragma mark -
@interface AFHTTPRequestOperation ()
@property (readwrite, nonatomic, strong) NSURLRequest *request;
@property (readwrite, nonatomic, strong) NSHTTPURLResponse *response;
@property (readwrite, nonatomic, strong) NSError *HTTPError;
@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
@end
@implementation AFHTTPRequestOperation
@synthesize HTTPError = _HTTPError;
@synthesize successCallbackQueue = _successCallbackQueue;
@synthesize failureCallbackQueue = _failureCallbackQueue;
@dynamic lock;
@dynamic request;
@dynamic response;
- (void)dealloc {
if (_successCallbackQueue) {
#if !OS_OBJECT_USE_OBJC
dispatch_release(_successCallbackQueue);
#endif
_successCallbackQueue = NULL;
}
if (_failureCallbackQueue) {
#if !OS_OBJECT_USE_OBJC
dispatch_release(_failureCallbackQueue);
#endif
_failureCallbackQueue = NULL;
}
}
- (NSError *)error {
[self.lock lock];
if (!self.HTTPError && self.response) {
if (![self hasAcceptableStatusCode] || ![self hasAcceptableContentType]) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setValue:self.responseString forKey:NSLocalizedRecoverySuggestionErrorKey];
[userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
[userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey];
[userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey];
if (![self hasAcceptableStatusCode]) {
NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
[userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected status code in (%@), got %d", @"AFNetworking", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), statusCode] forKey:NSLocalizedDescriptionKey];
self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo];
} else if (![self hasAcceptableContentType]) {
// Don't invalidate content type if there is no content
if ([self.responseData length] > 0) {
[userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected content type %@, got %@", @"AFNetworking", nil), [[self class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey];
self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
}
}
}
}
[self.lock unlock];
if (self.HTTPError) {
return self.HTTPError;
} else {
return [super error];
}
}
- (NSStringEncoding)responseStringEncoding {
// When no explicit charset parameter is provided by the sender, media subtypes of the "text" type are defined to have a default charset value of "ISO-8859-1" when received via HTTP. Data in character sets other than "ISO-8859-1" or its subsets MUST be labeled with an appropriate charset value.
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.4.1
if (self.response && !self.response.textEncodingName && self.responseData && [self.response respondsToSelector:@selector(allHeaderFields)]) {
NSString *type = nil;
AFGetMediaTypeAndSubtypeWithString([[self.response allHeaderFields] valueForKey:@"Content-Type"], &type, nil);
if ([type isEqualToString:@"text"]) {
return NSISOLatin1StringEncoding;
}
}
return [super responseStringEncoding];
}
- (void)pause {
unsigned long long offset = 0;
if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
} else {
offset = [[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length];
}
NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy];
if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) {
[mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"];
}
[mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
self.request = mutableURLRequest;
[super pause];
}
- (BOOL)hasAcceptableStatusCode {
if (!self.response) {
return NO;
}
NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode];
}
- (BOOL)hasAcceptableContentType {
if (!self.response) {
return NO;
}
// Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html
NSString *contentType = [self.response MIMEType];
if (!contentType) {
contentType = @"application/octet-stream";
}
return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType];
}
- (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue {
if (successCallbackQueue != _successCallbackQueue) {
if (_successCallbackQueue) {
#if !OS_OBJECT_USE_OBJC
dispatch_release(_successCallbackQueue);
#endif
_successCallbackQueue = NULL;
}
if (successCallbackQueue) {
#if !OS_OBJECT_USE_OBJC
dispatch_retain(successCallbackQueue);
#endif
_successCallbackQueue = successCallbackQueue;
}
}
}
- (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue {
if (failureCallbackQueue != _failureCallbackQueue) {
if (_failureCallbackQueue) {
#if !OS_OBJECT_USE_OBJC
dispatch_release(_failureCallbackQueue);
#endif
_failureCallbackQueue = NULL;
}
if (failureCallbackQueue) {
#if !OS_OBJECT_USE_OBJC
dispatch_retain(failureCallbackQueue);
#endif
_failureCallbackQueue = failureCallbackQueue;
}
}
}
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
// completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
self.completionBlock = ^{
if (self.error) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
success(self, self.responseData);
});
}
}
};
#pragma clang diagnostic pop
}
#pragma mark - AFHTTPRequestOperation
+ (NSIndexSet *)acceptableStatusCodes {
return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
}
+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes {
NSMutableIndexSet *mutableStatusCodes = [[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]];
[mutableStatusCodes addIndexes:statusCodes];
AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableStatusCodes), ^(__unused id _self) {
return mutableStatusCodes;
});
}
+ (NSSet *)acceptableContentTypes {
return nil;
}
+ (void)addAcceptableContentTypes:(NSSet *)contentTypes {
NSMutableSet *mutableContentTypes = [[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES];
[mutableContentTypes unionSet:contentTypes];
AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableContentTypes), ^(__unused id _self) {
return mutableContentTypes;
});
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
if ([[self class] isEqual:[AFHTTPRequestOperation class]]) {
return YES;
}
return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])];
}
@end
#pragma clang diagnostic pop

View File

@ -0,0 +1,113 @@
// AFImageRequestOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
#import <Availability.h>
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
#import <Cocoa/Cocoa.h>
#endif
/**
`AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and processing images.
## Acceptable Content Types
By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
- `image/tiff`
- `image/jpeg`
- `image/gif`
- `image/png`
- `image/ico`
- `image/x-icon`
- `image/bmp`
- `image/x-bmp`
- `image/x-xbitmap`
- `image/x-win-bitmap`
*/
@interface AFImageRequestOperation : AFHTTPRequestOperation
/**
An image constructed from the response data. If an error occurs during the request, `nil` will be returned, and the `error` property will be set to the error.
*/
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
@property (readonly, nonatomic, strong) UIImage *responseImage;
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
@property (readonly, nonatomic, strong) NSImage *responseImage;
#endif
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
/**
The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance.
*/
@property (nonatomic, assign) CGFloat imageScale;
/**
Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default.
*/
@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
#endif
/**
Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
@param urlRequest The request object to be loaded asynchronously during execution of the operation.
@param success A block object to be executed when the request finishes successfully. This block has no return value and takes a single argument, the image created from the response data of the request.
@return A new image request operation
*/
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(UIImage *image))success;
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSImage *image))success;
#endif
/**
Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
@param urlRequest The request object to be loaded asynchronously during execution of the operation.
@param imageProcessingBlock A block object to be executed after the image request finishes successfully, but before the image is returned in the `success` block. This block takes a single argument, the image loaded from the response body, and returns the processed image.
@param success A block object to be executed when the request finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the image created from the response data.
@param failure A block object to be executed when the request finishes unsuccessfully. This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the error associated with the cause for the unsuccessful operation.
@return A new image request operation
*/
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
imageProcessingBlock:(UIImage *(^)(UIImage *image))imageProcessingBlock
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
imageProcessingBlock:(NSImage *(^)(NSImage *image))imageProcessingBlock
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
#endif
@end

View File

@ -0,0 +1,321 @@
// AFImageRequestOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFImageRequestOperation.h"
static dispatch_queue_t image_request_operation_processing_queue() {
static dispatch_queue_t af_image_request_operation_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", DISPATCH_QUEUE_CONCURRENT);
});
return af_image_request_operation_processing_queue;
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <CoreGraphics/CoreGraphics.h>
static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
UIImage *image = [[UIImage alloc] initWithData:data];
return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
}
static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
if (!data || [data length] == 0) {
return nil;
}
UIImage *image = AFImageWithDataAtScale(data, scale);
if (image.images) {
return image;
}
CGImageRef imageRef = nil;
CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
if ([response.MIMEType isEqualToString:@"image/png"]) {
imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
} else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
}
if (!imageRef) {
imageRef = CGImageCreateCopy([image CGImage]);
if (!imageRef) {
CGDataProviderRelease(dataProvider);
return image;
}
}
CGDataProviderRelease(dataProvider);
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);
size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
size_t bytesPerRow = 0; // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate()
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
if (CGColorSpaceGetNumberOfComponents(colorSpace) == 3) {
int alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
if (alpha == kCGImageAlphaNone) {
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
bitmapInfo |= kCGImageAlphaNoneSkipFirst;
} else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
bitmapInfo |= kCGImageAlphaPremultipliedFirst;
}
}
CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
CGColorSpaceRelease(colorSpace);
if (!context) {
CGImageRelease(imageRef);
return image;
}
CGRect rect = CGRectMake(0.0f, 0.0f, width, height);
CGContextDrawImage(context, rect, imageRef);
CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
CGImageRelease(inflatedImageRef);
CGImageRelease(imageRef);
return inflatedImage;
}
#endif
@interface AFImageRequestOperation ()
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
@property (readwrite, nonatomic, strong) UIImage *responseImage;
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
@property (readwrite, nonatomic, strong) NSImage *responseImage;
#endif
@end
@implementation AFImageRequestOperation
@synthesize responseImage = _responseImage;
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
@synthesize imageScale = _imageScale;
#endif
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(UIImage *image))success
{
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
if (success) {
success(image);
}
} failure:nil];
}
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSImage *image))success
{
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
if (success) {
success(image);
}
} failure:nil];
}
#endif
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
UIImage *image = responseObject;
if (imageProcessingBlock) {
dispatch_async(image_request_operation_processing_queue(), ^(void) {
UIImage *processedImage = imageProcessingBlock(image);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) {
success(operation.request, operation.response, processedImage);
});
#pragma clang diagnostic pop
});
} else {
success(operation.request, operation.response, image);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(operation.request, operation.response, error);
}
}];
return requestOperation;
}
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
NSImage *image = responseObject;
if (imageProcessingBlock) {
dispatch_async(image_request_operation_processing_queue(), ^(void) {
NSImage *processedImage = imageProcessingBlock(image);
dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) {
success(operation.request, operation.response, processedImage);
});
});
} else {
success(operation.request, operation.response, image);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(operation.request, operation.response, error);
}
}];
return requestOperation;
}
#endif
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
self.imageScale = [[UIScreen mainScreen] scale];
self.automaticallyInflatesResponseImage = YES;
#endif
return self;
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
- (UIImage *)responseImage {
if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
if (self.automaticallyInflatesResponseImage) {
self.responseImage = AFInflatedImageFromResponseWithDataAtScale(self.response, self.responseData, self.imageScale);
} else {
self.responseImage = AFImageWithDataAtScale(self.responseData, self.imageScale);
}
}
return _responseImage;
}
- (void)setImageScale:(CGFloat)imageScale {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wfloat-equal"
if (imageScale == _imageScale) {
return;
}
#pragma clang diagnostic pop
_imageScale = imageScale;
self.responseImage = nil;
}
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
- (NSImage *)responseImage {
if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
// Ensure that the image is set to it's correct pixel width and height
NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:self.responseData];
self.responseImage = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
[self.responseImage addRepresentation:bitimage];
}
return _responseImage;
}
#endif
#pragma mark - AFHTTPRequestOperation
+ (NSSet *)acceptableContentTypes {
return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
static NSSet * _acceptablePathExtension = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
});
return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request];
}
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
self.completionBlock = ^ {
dispatch_async(image_request_operation_processing_queue(), ^(void) {
if (self.error) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
UIImage *image = nil;
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
NSImage *image = nil;
#endif
image = self.responseImage;
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
success(self, image);
});
}
}
});
};
#pragma clang diagnostic pop
}
@end

View File

@ -0,0 +1,71 @@
// AFJSONRequestOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
/**
`AFJSONRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with JSON response data.
## Acceptable Content Types
By default, `AFJSONRequestOperation` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
- `application/json`
- `text/json`
@warning JSON parsing will use the built-in `NSJSONSerialization` class.
*/
@interface AFJSONRequestOperation : AFHTTPRequestOperation
///----------------------------
/// @name Getting Response Data
///----------------------------
/**
A JSON object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error.
*/
@property (readonly, nonatomic, strong) id responseJSON;
/**
Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions".
*/
@property (nonatomic, assign) NSJSONReadingOptions JSONReadingOptions;
///----------------------------------
/// @name Creating Request Operations
///----------------------------------
/**
Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks.
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the JSON object created from the response data of request.
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as JSON. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
@return A new JSON request operation
*/
+ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;
@end

View File

@ -0,0 +1,150 @@
// AFJSONRequestOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFJSONRequestOperation.h"
static dispatch_queue_t json_request_operation_processing_queue() {
static dispatch_queue_t af_json_request_operation_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", DISPATCH_QUEUE_CONCURRENT);
});
return af_json_request_operation_processing_queue;
}
@interface AFJSONRequestOperation ()
@property (readwrite, nonatomic, strong) id responseJSON;
@property (readwrite, nonatomic, strong) NSError *JSONError;
@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
@end
@implementation AFJSONRequestOperation
@synthesize responseJSON = _responseJSON;
@synthesize JSONReadingOptions = _JSONReadingOptions;
@synthesize JSONError = _JSONError;
@dynamic lock;
+ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure
{
AFJSONRequestOperation *requestOperation = [(AFJSONRequestOperation *)[self alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success(operation.request, operation.response, responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]);
}
}];
return requestOperation;
}
- (id)responseJSON {
[self.lock lock];
if (!_responseJSON && [self.responseData length] > 0 && [self isFinished] && !self.JSONError) {
NSError *error = nil;
// Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization.
// See https://github.com/rails/rails/issues/1742
if (self.responseString && ![self.responseString isEqualToString:@" "]) {
// Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character
// See http://stackoverflow.com/a/12843465/157142
NSData *data = [self.responseString dataUsingEncoding:NSUTF8StringEncoding];
if (data) {
self.responseJSON = [NSJSONSerialization JSONObjectWithData:data options:self.JSONReadingOptions error:&error];
} else {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setValue:@"Operation responseData failed decoding as a UTF-8 string" forKey:NSLocalizedDescriptionKey];
[userInfo setValue:[NSString stringWithFormat:@"Could not decode string: %@", self.responseString] forKey:NSLocalizedFailureReasonErrorKey];
error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
}
}
self.JSONError = error;
}
[self.lock unlock];
return _responseJSON;
}
- (NSError *)error {
if (_JSONError) {
return _JSONError;
} else {
return [super error];
}
}
#pragma mark - AFHTTPRequestOperation
+ (NSSet *)acceptableContentTypes {
return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[[request URL] pathExtension] isEqualToString:@"json"] || [super canProcessRequest:request];
}
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
self.completionBlock = ^ {
if (self.error) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
dispatch_async(json_request_operation_processing_queue(), ^{
id JSON = self.responseJSON;
if (self.error) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
success(self, JSON);
});
}
}
});
}
};
#pragma clang diagnostic pop
}
@end

View File

@ -0,0 +1,75 @@
// AFNetworkActivityIndicatorManager.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <Availability.h>
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
/**
`AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a network request operation has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero.
You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code:
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
By setting `isNetworkActivityIndicatorVisible` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself.
See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information:
http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44
*/
@interface AFNetworkActivityIndicatorManager : NSObject
/**
A Boolean value indicating whether the manager is enabled.
If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO.
*/
@property (nonatomic, assign, getter = isEnabled) BOOL enabled;
/**
A Boolean value indicating whether the network activity indicator is currently displayed in the status bar.
*/
@property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible;
/**
Returns the shared network activity indicator manager object for the system.
@return The systemwide network activity indicator manager.
*/
+ (instancetype)sharedManager;
/**
Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator.
*/
- (void)incrementActivityCount;
/**
Decrements the number of active network requests. If this number becomes zero before decrementing, this will stop animating the status bar network activity indicator.
*/
- (void)decrementActivityCount;
@end
#endif

View File

@ -0,0 +1,157 @@
// AFNetworkActivityIndicatorManager.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFNetworkActivityIndicatorManager.h"
#import "AFHTTPRequestOperation.h"
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
@interface AFNetworkActivityIndicatorManager ()
@property (readwrite, nonatomic, assign) NSInteger activityCount;
@property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer;
@property (readonly, nonatomic, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
- (void)updateNetworkActivityIndicatorVisibility;
- (void)updateNetworkActivityIndicatorVisibilityDelayed;
@end
@implementation AFNetworkActivityIndicatorManager
@synthesize activityCount = _activityCount;
@synthesize activityIndicatorVisibilityTimer = _activityIndicatorVisibilityTimer;
@synthesize enabled = _enabled;
@dynamic networkActivityIndicatorVisible;
+ (instancetype)sharedManager {
static AFNetworkActivityIndicatorManager *_sharedManager = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedManager = [[self alloc] init];
});
return _sharedManager;
}
+ (NSSet *)keyPathsForValuesAffectingIsNetworkActivityIndicatorVisible {
return [NSSet setWithObject:@"activityCount"];
}
- (id)init {
self = [super init];
if (!self) {
return nil;
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingOperationDidStart:) name:AFNetworkingOperationDidStartNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingOperationDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil];
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[_activityIndicatorVisibilityTimer invalidate];
}
- (void)updateNetworkActivityIndicatorVisibilityDelayed {
if (self.enabled) {
// Delay hiding of activity indicator for a short interval, to avoid flickering
if (![self isNetworkActivityIndicatorVisible]) {
[self.activityIndicatorVisibilityTimer invalidate];
self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes];
} else {
[self performSelectorOnMainThread:@selector(updateNetworkActivityIndicatorVisibility) withObject:nil waitUntilDone:NO modes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
}
}
}
- (BOOL)isNetworkActivityIndicatorVisible {
return _activityCount > 0;
}
- (void)updateNetworkActivityIndicatorVisibility {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]];
}
// Not exposed, but used if activityCount is set via KVC.
- (NSInteger)activityCount {
return _activityCount;
}
- (void)setActivityCount:(NSInteger)activityCount {
@synchronized(self) {
_activityCount = activityCount;
}
dispatch_async(dispatch_get_main_queue(), ^{
[self updateNetworkActivityIndicatorVisibilityDelayed];
});
}
- (void)incrementActivityCount {
[self willChangeValueForKey:@"activityCount"];
@synchronized(self) {
_activityCount++;
}
[self didChangeValueForKey:@"activityCount"];
dispatch_async(dispatch_get_main_queue(), ^{
[self updateNetworkActivityIndicatorVisibilityDelayed];
});
}
- (void)decrementActivityCount {
[self willChangeValueForKey:@"activityCount"];
@synchronized(self) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
_activityCount = MAX(_activityCount - 1, 0);
#pragma clang diagnostic pop
}
[self didChangeValueForKey:@"activityCount"];
dispatch_async(dispatch_get_main_queue(), ^{
[self updateNetworkActivityIndicatorVisibilityDelayed];
});
}
- (void)networkingOperationDidStart:(NSNotification *)notification {
AFURLConnectionOperation *connectionOperation = [notification object];
if (connectionOperation.request.URL) {
[self incrementActivityCount];
}
}
- (void)networkingOperationDidFinish:(NSNotification *)notification {
AFURLConnectionOperation *connectionOperation = [notification object];
if (connectionOperation.request.URL) {
[self decrementActivityCount];
}
}
@end
#endif

View File

@ -0,0 +1,43 @@
// AFNetworking.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <Availability.h>
#ifndef _AFNETWORKING_
#define _AFNETWORKING_
#import "AFURLConnectionOperation.h"
#import "AFHTTPRequestOperation.h"
#import "AFJSONRequestOperation.h"
#import "AFXMLRequestOperation.h"
#import "AFPropertyListRequestOperation.h"
#import "AFHTTPClient.h"
#import "AFImageRequestOperation.h"
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import "AFNetworkActivityIndicatorManager.h"
#import "UIImageView+AFNetworking.h"
#endif
#endif /* _AFNETWORKING_ */

View File

@ -0,0 +1,68 @@
// AFPropertyListRequestOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
/**
`AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and deserializing objects with property list (plist) response data.
## Acceptable Content Types
By default, `AFPropertyListRequestOperation` accepts the following MIME types:
- `application/x-plist`
*/
@interface AFPropertyListRequestOperation : AFHTTPRequestOperation
///----------------------------
/// @name Getting Response Data
///----------------------------
/**
An object deserialized from a plist constructed using the response data.
*/
@property (readonly, nonatomic) id responsePropertyList;
///--------------------------------------
/// @name Managing Property List Behavior
///--------------------------------------
/**
One of the `NSPropertyListMutabilityOptions` options, specifying the mutability of objects deserialized from the property list. By default, this is `NSPropertyListImmutable`.
*/
@property (nonatomic, assign) NSPropertyListReadOptions propertyListReadOptions;
/**
Creates and returns an `AFPropertyListRequestOperation` object and sets the specified success and failure callbacks.
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the object deserialized from a plist constructed using the response data.
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while deserializing the object from a property list. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
@return A new property list request operation
*/
+ (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure;
@end

View File

@ -0,0 +1,143 @@
// AFPropertyListRequestOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFPropertyListRequestOperation.h"
static dispatch_queue_t property_list_request_operation_processing_queue() {
static dispatch_queue_t af_property_list_request_operation_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_property_list_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.property-list-request.processing", DISPATCH_QUEUE_CONCURRENT);
});
return af_property_list_request_operation_processing_queue;
}
@interface AFPropertyListRequestOperation ()
@property (readwrite, nonatomic) id responsePropertyList;
@property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat;
@property (readwrite, nonatomic) NSError *propertyListError;
@end
@implementation AFPropertyListRequestOperation
@synthesize responsePropertyList = _responsePropertyList;
@synthesize propertyListReadOptions = _propertyListReadOptions;
@synthesize propertyListFormat = _propertyListFormat;
@synthesize propertyListError = _propertyListError;
+ (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure
{
AFPropertyListRequestOperation *requestOperation = [(AFPropertyListRequestOperation *)[self alloc] initWithRequest:request];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success(operation.request, operation.response, responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(operation.request, operation.response, error, [(AFPropertyListRequestOperation *)operation responsePropertyList]);
}
}];
return requestOperation;
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.propertyListReadOptions = NSPropertyListImmutable;
return self;
}
- (id)responsePropertyList {
if (!_responsePropertyList && [self.responseData length] > 0 && [self isFinished]) {
NSPropertyListFormat format;
NSError *error = nil;
self.responsePropertyList = [NSPropertyListSerialization propertyListWithData:self.responseData options:self.propertyListReadOptions format:&format error:&error];
self.propertyListFormat = format;
self.propertyListError = error;
}
return _responsePropertyList;
}
- (NSError *)error {
if (_propertyListError) {
return _propertyListError;
} else {
return [super error];
}
}
#pragma mark - AFHTTPRequestOperation
+ (NSSet *)acceptableContentTypes {
return [NSSet setWithObjects:@"application/x-plist", nil];
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[[request URL] pathExtension] isEqualToString:@"plist"] || [super canProcessRequest:request];
}
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
self.completionBlock = ^ {
if (self.error) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
dispatch_async(property_list_request_operation_processing_queue(), ^(void) {
id propertyList = self.responsePropertyList;
if (self.propertyListError) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
success(self, propertyList);
});
}
}
});
}
};
#pragma clang diagnostic pop
}
@end

View File

@ -0,0 +1,370 @@
// AFURLConnectionOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <Availability.h>
/**
`AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods.
## Subclassing Notes
This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors.
If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes.
## NSURLConnection Delegate Methods
`AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods:
- `connection:didReceiveResponse:`
- `connection:didReceiveData:`
- `connectionDidFinishLoading:`
- `connection:didFailWithError:`
- `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:`
- `connection:willCacheResponse:`
- `connectionShouldUseCredentialStorage:`
- `connection:willSendRequestForAuthenticationChallenge:`
If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
## Class Constructors
Class constructors, or methods that return an unowned instance, are the preferred way for subclasses to encapsulate any particular logic for handling the setup or parsing of response data. For instance, `AFJSONRequestOperation` provides `JSONRequestOperationWithRequest:success:failure:`, which takes block arguments, whose parameter on for a successful request is the JSON object initialized from the `response data`.
## Callbacks and Completion Blocks
The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this.
Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/).
## SSL Pinning
Relying on the CA trust model to validate SSL certificates exposes your app to security vulnerabilities, such as man-in-the-middle attacks. For applications that connect to known servers, SSL certificate pinning provides an increased level of security, by checking server certificate validity against those specified in the app bundle.
SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice.
When `defaultSSLPinningMode` is defined on `AFHTTPClient` and the Security framework is linked, connections will be validated on all matching certificates with a `.cer` extension in the bundle root.
## NSCoding & NSCopying Conformance
`AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind:
### NSCoding Caveats
- Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`.
- Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged.
### NSCopying Caveats
- `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations.
- A copy of an operation will not include the `outputStream` of the original.
- Operation copies do not include `completionBlock`. `completionBlock` often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied.
*/
typedef enum {
AFSSLPinningModeNone,
AFSSLPinningModePublicKey,
AFSSLPinningModeCertificate,
} AFURLConnectionOperationSSLPinningMode;
@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate,
#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 50000) || \
(defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080)
NSURLConnectionDataDelegate,
#endif
NSCoding, NSCopying>
///-------------------------------
/// @name Accessing Run Loop Modes
///-------------------------------
/**
The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`.
*/
@property (nonatomic, strong) NSSet *runLoopModes;
///-----------------------------------------
/// @name Getting URL Connection Information
///-----------------------------------------
/**
The request used by the operation's connection.
*/
@property (readonly, nonatomic, strong) NSURLRequest *request;
/**
The last response received by the operation's connection.
*/
@property (readonly, nonatomic, strong) NSURLResponse *response;
/**
The error, if any, that occurred in the lifecycle of the request.
*/
@property (readonly, nonatomic, strong) NSError *error;
/**
Whether the connection should accept an invalid SSL certificate.
If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is set, this property defaults to `YES` for backwards compatibility. Otherwise, this property defaults to `NO`.
*/
@property (nonatomic, assign) BOOL allowsInvalidSSLCertificate;
///----------------------------
/// @name Getting Response Data
///----------------------------
/**
The data received during the request.
*/
@property (readonly, nonatomic, strong) NSData *responseData;
/**
The string representation of the response data.
*/
@property (readonly, nonatomic, copy) NSString *responseString;
/**
The string encoding of the response.
If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`.
*/
@property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding;
///-------------------------------
/// @name Managing URL Credentials
///-------------------------------
/**
Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
*/
@property (nonatomic, assign) BOOL shouldUseCredentialStorage;
/**
The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
*/
@property (nonatomic, strong) NSURLCredential *credential;
/**
The pinning mode which will be used for SSL connections. `AFSSLPinningModePublicKey` by default.
SSL Pinning requires that the Security framework is linked with the binary. See the "SSL Pinning" section in the `AFURLConnectionOperation`" header for more information.
*/
@property (nonatomic, assign) AFURLConnectionOperationSSLPinningMode SSLPinningMode;
///------------------------
/// @name Accessing Streams
///------------------------
/**
The input stream used to read data to be sent during the request.
This property acts as a proxy to the `HTTPBodyStream` property of `request`.
*/
@property (nonatomic, strong) NSInputStream *inputStream;
/**
The output stream that is used to write data received until the request is finished.
By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set.
*/
@property (nonatomic, strong) NSOutputStream *outputStream;
///---------------------------------------------
/// @name Managing Request Operation Information
///---------------------------------------------
/**
The user info dictionary for the receiver.
*/
@property (nonatomic, strong) NSDictionary *userInfo;
///------------------------------------------------------
/// @name Initializing an AFURLConnectionOperation Object
///------------------------------------------------------
/**
Initializes and returns a newly allocated operation object with a url connection configured with the specified url request.
This is the designated initializer.
@param urlRequest The request object to be used by the operation connection.
*/
- (id)initWithRequest:(NSURLRequest *)urlRequest;
///----------------------------------
/// @name Pausing / Resuming Requests
///----------------------------------
/**
Pauses the execution of the request operation.
A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect.
*/
- (void)pause;
/**
Whether the request operation is currently paused.
@return `YES` if the operation is currently paused, otherwise `NO`.
*/
- (BOOL)isPaused;
/**
Resumes the execution of the paused request operation.
Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request.
*/
- (void)resume;
///----------------------------------------------
/// @name Configuring Backgrounding Task Behavior
///----------------------------------------------
/**
Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task.
@param handler A handler to be called shortly before the applications remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the applications suspension momentarily while the application is notified.
*/
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler;
#endif
///---------------------------------
/// @name Setting Progress Callbacks
///---------------------------------
/**
Sets a callback to be called when an undetermined number of bytes have been uploaded to the server.
@param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread.
*/
- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block;
/**
Sets a callback to be called when an undetermined number of bytes have been downloaded from the server.
@param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread.
*/
- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block;
///-------------------------------------------------
/// @name Setting NSURLConnection Delegate Callbacks
///-------------------------------------------------
/**
Sets a block to be executed when the connection will authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequestForAuthenticationChallenge:`.
@param block A block object to be executed when the connection will authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. This block must invoke one of the challenge-responder methods (NSURLAuthenticationChallengeSender protocol).
If `allowsInvalidSSLCertificate` is set to YES, `connection:willSendRequestForAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates.
*/
- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block;
/**
Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequest:redirectResponse:`.
@param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect.
*/
- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block;
/**
Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`.
@param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request.
*/
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;
@end
///----------------
/// @name Constants
///----------------
/**
## SSL Pinning Options
The following constants are provided by `AFURLConnectionOperation` as possible SSL Pinning options.
enum {
AFSSLPinningModeNone,
AFSSLPinningModePublicKey,
AFSSLPinningModeCertificate,
}
`AFSSLPinningModeNone`
Do not pin SSL connections
`AFSSLPinningModePublicKey`
Pin SSL connections to certificate public key (SPKI).
`AFSSLPinningModeCertificate`
Pin SSL connections to exact certificate. This may cause problems when your certificate expires and needs re-issuance.
## User info dictionary keys
These keys may exist in the user info dictionary, in addition to those defined for NSError.
- `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
- `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
### Constants
`AFNetworkingOperationFailingURLRequestErrorKey`
The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`.
`AFNetworkingOperationFailingURLResponseErrorKey`
The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`.
## Error Domains
The following error domain is predefined.
- `NSString * const AFNetworkingErrorDomain`
### Constants
`AFNetworkingErrorDomain`
AFNetworking errors. Error codes for `AFNetworkingErrorDomain` correspond to codes in `NSURLErrorDomain`.
*/
extern NSString * const AFNetworkingErrorDomain;
extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
///--------------------
/// @name Notifications
///--------------------
/**
Posted when an operation begins executing.
*/
extern NSString * const AFNetworkingOperationDidStartNotification;
/**
Posted when an operation finishes.
*/
extern NSString * const AFNetworkingOperationDidFinishNotification;

View File

@ -0,0 +1,848 @@
// AFURLConnectionOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFURLConnectionOperation.h"
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
#endif
#if !__has_feature(objc_arc)
#error AFNetworking must be built with ARC.
// You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files.
#endif
typedef enum {
AFOperationPausedState = -1,
AFOperationReadyState = 1,
AFOperationExecutingState = 2,
AFOperationFinishedState = 3,
} _AFOperationState;
typedef signed short AFOperationState;
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
typedef UIBackgroundTaskIdentifier AFBackgroundTaskIdentifier;
#else
typedef id AFBackgroundTaskIdentifier;
#endif
static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock";
NSString * const AFNetworkingErrorDomain = @"AFNetworkingErrorDomain";
NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"AFNetworkingOperationFailingURLRequestErrorKey";
NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"AFNetworkingOperationFailingURLResponseErrorKey";
NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start";
NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish";
typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected);
typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge);
typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse);
typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse);
static inline NSString * AFKeyPathFromOperationState(AFOperationState state) {
switch (state) {
case AFOperationReadyState:
return @"isReady";
case AFOperationExecutingState:
return @"isExecuting";
case AFOperationFinishedState:
return @"isFinished";
case AFOperationPausedState:
return @"isPaused";
default:
return @"state";
}
}
static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperationState toState, BOOL isCancelled) {
switch (fromState) {
case AFOperationReadyState:
switch (toState) {
case AFOperationPausedState:
case AFOperationExecutingState:
return YES;
case AFOperationFinishedState:
return isCancelled;
default:
return NO;
}
case AFOperationExecutingState:
switch (toState) {
case AFOperationPausedState:
case AFOperationFinishedState:
return YES;
default:
return NO;
}
case AFOperationFinishedState:
return NO;
case AFOperationPausedState:
return toState == AFOperationReadyState;
default:
return YES;
}
}
#if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
static NSData *AFSecKeyGetData(SecKeyRef key) {
CFDataRef data = NULL;
OSStatus status = SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data);
NSCAssert(status == errSecSuccess, @"SecItemExport error: %ld", (long int)status);
NSCParameterAssert(data);
return (__bridge_transfer NSData *)data;
}
#endif
static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
return [(__bridge id)key1 isEqual:(__bridge id)key2];
#else
return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
#endif
}
@interface AFURLConnectionOperation ()
@property (readwrite, nonatomic, assign) AFOperationState state;
@property (readwrite, nonatomic, assign, getter = isCancelled) BOOL cancelled;
@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
@property (readwrite, nonatomic, strong) NSURLConnection *connection;
@property (readwrite, nonatomic, strong) NSURLRequest *request;
@property (readwrite, nonatomic, strong) NSURLResponse *response;
@property (readwrite, nonatomic, strong) NSError *error;
@property (readwrite, nonatomic, strong) NSData *responseData;
@property (readwrite, nonatomic, copy) NSString *responseString;
@property (readwrite, nonatomic, assign) NSStringEncoding responseStringEncoding;
@property (readwrite, nonatomic, assign) long long totalBytesRead;
@property (readwrite, nonatomic, assign) AFBackgroundTaskIdentifier backgroundTaskIdentifier;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationCacheResponseBlock cacheResponse;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationRedirectResponseBlock redirectResponse;
- (void)operationDidStart;
- (void)finish;
- (void)cancelConnection;
@end
@implementation AFURLConnectionOperation
@synthesize state = _state;
@synthesize cancelled = _cancelled;
@synthesize connection = _connection;
@synthesize runLoopModes = _runLoopModes;
@synthesize request = _request;
@synthesize response = _response;
@synthesize error = _error;
@synthesize allowsInvalidSSLCertificate = _allowsInvalidSSLCertificate;
@synthesize responseData = _responseData;
@synthesize responseString = _responseString;
@synthesize responseStringEncoding = _responseStringEncoding;
@synthesize totalBytesRead = _totalBytesRead;
@dynamic inputStream;
@synthesize outputStream = _outputStream;
@synthesize credential = _credential;
@synthesize SSLPinningMode = _SSLPinningMode;
@synthesize shouldUseCredentialStorage = _shouldUseCredentialStorage;
@synthesize userInfo = _userInfo;
@synthesize backgroundTaskIdentifier = _backgroundTaskIdentifier;
@synthesize uploadProgress = _uploadProgress;
@synthesize downloadProgress = _downloadProgress;
@synthesize authenticationChallenge = _authenticationChallenge;
@synthesize cacheResponse = _cacheResponse;
@synthesize redirectResponse = _redirectResponse;
@synthesize lock = _lock;
+ (void)networkRequestThreadEntryPoint:(id __unused)object {
@autoreleasepool {
[[NSThread currentThread] setName:@"AFNetworking"];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
[runLoop run];
}
}
+ (NSThread *)networkRequestThread {
static NSThread *_networkRequestThread = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
[_networkRequestThread start];
});
return _networkRequestThread;
}
+ (NSArray *)pinnedCertificates {
static NSArray *_pinnedCertificates = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSBundle *bundle = [NSBundle mainBundle];
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]];
for (NSString *path in paths) {
NSData *certificateData = [NSData dataWithContentsOfFile:path];
[certificates addObject:certificateData];
}
_pinnedCertificates = [[NSArray alloc] initWithArray:certificates];
});
return _pinnedCertificates;
}
+ (NSArray *)pinnedPublicKeys {
static NSArray *_pinnedPublicKeys = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSArray *pinnedCertificates = [self pinnedCertificates];
NSMutableArray *publicKeys = [NSMutableArray arrayWithCapacity:[pinnedCertificates count]];
for (NSData *data in pinnedCertificates) {
SecCertificateRef allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)data);
NSParameterAssert(allowedCertificate);
SecCertificateRef allowedCertificates[] = {allowedCertificate};
CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
SecPolicyRef policy = SecPolicyCreateBasicX509();
SecTrustRef allowedTrust = NULL;
OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &allowedTrust);
NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);
if (status == errSecSuccess && allowedTrust) {
SecTrustResultType result = 0;
status = SecTrustEvaluate(allowedTrust, &result);
NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
if (status == errSecSuccess) {
SecKeyRef allowedPublicKey = SecTrustCopyPublicKey(allowedTrust);
NSParameterAssert(allowedPublicKey);
if (allowedPublicKey) {
[publicKeys addObject:(__bridge_transfer id)allowedPublicKey];
}
}
CFRelease(allowedTrust);
}
CFRelease(policy);
CFRelease(certificates);
CFRelease(allowedCertificate);
}
_pinnedPublicKeys = [[NSArray alloc] initWithArray:publicKeys];
});
return _pinnedPublicKeys;
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
NSParameterAssert(urlRequest);
self = [super init];
if (!self) {
return nil;
}
self.lock = [[NSRecursiveLock alloc] init];
self.lock.name = kAFNetworkingLockName;
self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes];
self.request = urlRequest;
self.shouldUseCredentialStorage = YES;
// #ifdef included for backwards-compatibility
#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
self.allowsInvalidSSLCertificate = YES;
#endif
self.state = AFOperationReadyState;
return self;
}
- (void)dealloc {
if (_outputStream) {
[_outputStream close];
_outputStream = nil;
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
if (_backgroundTaskIdentifier) {
[[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
_backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
#endif
}
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response];
}
- (void)setCompletionBlock:(void (^)(void))block {
[self.lock lock];
if (!block) {
[super setCompletionBlock:nil];
} else {
__weak __typeof(&*self)weakSelf = self;
[super setCompletionBlock:^ {
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
block();
[strongSelf setCompletionBlock:nil];
}];
}
[self.lock unlock];
}
- (NSInputStream *)inputStream {
return self.request.HTTPBodyStream;
}
- (void)setInputStream:(NSInputStream *)inputStream {
[self willChangeValueForKey:@"inputStream"];
NSMutableURLRequest *mutableRequest = [self.request mutableCopy];
mutableRequest.HTTPBodyStream = inputStream;
self.request = mutableRequest;
[self didChangeValueForKey:@"inputStream"];
}
- (NSOutputStream *)outputStream {
if (!_outputStream) {
self.outputStream = [NSOutputStream outputStreamToMemory];
}
return _outputStream;
}
- (void)setOutputStream:(NSOutputStream *)outputStream {
[self.lock lock];
if (outputStream != _outputStream) {
[self willChangeValueForKey:@"outputStream"];
if (_outputStream) {
[_outputStream close];
}
_outputStream = outputStream;
[self didChangeValueForKey:@"outputStream"];
}
[self.lock unlock];
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
[self.lock lock];
if (!self.backgroundTaskIdentifier) {
UIApplication *application = [UIApplication sharedApplication];
__weak __typeof(&*self)weakSelf = self;
self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
if (handler) {
handler();
}
if (strongSelf) {
[strongSelf cancel];
[application endBackgroundTask:strongSelf.backgroundTaskIdentifier];
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
}];
}
[self.lock unlock];
}
#endif
- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block {
self.uploadProgress = block;
}
- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block {
self.downloadProgress = block;
}
- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block {
self.authenticationChallenge = block;
}
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block {
self.cacheResponse = block;
}
- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block {
self.redirectResponse = block;
}
- (void)setState:(AFOperationState)state {
if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) {
return;
}
[self.lock lock];
NSString *oldStateKey = AFKeyPathFromOperationState(self.state);
NSString *newStateKey = AFKeyPathFromOperationState(state);
[self willChangeValueForKey:newStateKey];
[self willChangeValueForKey:oldStateKey];
_state = state;
[self didChangeValueForKey:oldStateKey];
[self didChangeValueForKey:newStateKey];
[self.lock unlock];
}
- (NSString *)responseString {
[self.lock lock];
if (!_responseString && self.response && self.responseData) {
self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding];
}
[self.lock unlock];
return _responseString;
}
- (NSStringEncoding)responseStringEncoding {
[self.lock lock];
if (!_responseStringEncoding && self.response) {
NSStringEncoding stringEncoding = NSUTF8StringEncoding;
if (self.response.textEncodingName) {
CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName);
if (IANAEncoding != kCFStringEncodingInvalidId) {
stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding);
}
}
self.responseStringEncoding = stringEncoding;
}
[self.lock unlock];
return _responseStringEncoding;
}
- (void)pause {
if ([self isPaused] || [self isFinished] || [self isCancelled]) {
return;
}
[self.lock lock];
if ([self isExecuting]) {
[self.connection performSelector:@selector(cancel) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
dispatch_async(dispatch_get_main_queue(), ^{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
});
}
self.state = AFOperationPausedState;
[self.lock unlock];
}
- (BOOL)isPaused {
return self.state == AFOperationPausedState;
}
- (void)resume {
if (![self isPaused]) {
return;
}
[self.lock lock];
self.state = AFOperationReadyState;
[self start];
[self.lock unlock];
}
#pragma mark - NSOperation
- (BOOL)isReady {
return self.state == AFOperationReadyState && [super isReady];
}
- (BOOL)isExecuting {
return self.state == AFOperationExecutingState;
}
- (BOOL)isFinished {
return self.state == AFOperationFinishedState;
}
- (BOOL)isConcurrent {
return YES;
}
- (void)start {
[self.lock lock];
if ([self isReady]) {
self.state = AFOperationExecutingState;
[self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
}
[self.lock unlock];
}
- (void)operationDidStart {
[self.lock lock];
if (![self isCancelled]) {
self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
for (NSString *runLoopMode in self.runLoopModes) {
[self.connection scheduleInRunLoop:runLoop forMode:runLoopMode];
[self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
}
[self.connection start];
}
[self.lock unlock];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self];
});
if ([self isCancelled]) {
NSDictionary *userInfo = nil;
if ([self.request URL]) {
userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
}
self.error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
[self finish];
}
}
- (void)finish {
self.state = AFOperationFinishedState;
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
});
}
- (void)cancel {
[self.lock lock];
if (![self isFinished] && ![self isCancelled]) {
[self willChangeValueForKey:@"isCancelled"];
_cancelled = YES;
[super cancel];
[self didChangeValueForKey:@"isCancelled"];
// Cancel the connection on the thread it runs on to prevent race conditions
[self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
}
[self.lock unlock];
}
- (void)cancelConnection {
NSDictionary *userInfo = nil;
if ([self.request URL]) {
userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
}
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
if (![self isFinished] && self.connection) {
[self.connection cancel];
[self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error];
}
}
#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection
willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if (self.authenticationChallenge) {
self.authenticationChallenge(connection, challenge);
return;
}
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
SecPolicyRef policy = SecPolicyCreateBasicX509();
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:certificateCount];
for (CFIndex i = 0; i < certificateCount; i++) {
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
if (self.SSLPinningMode == AFSSLPinningModeCertificate) {
[trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
} else if (self.SSLPinningMode == AFSSLPinningModePublicKey) {
SecCertificateRef someCertificates[] = {certificate};
CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
SecTrustRef trust = NULL;
OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust);
NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);
if (status == errSecSuccess && trust) {
SecTrustResultType result;
status = SecTrustEvaluate(trust, &result);
NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
if (status == errSecSuccess) {
[trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
}
CFRelease(trust);
}
CFRelease(certificates);
}
}
CFRelease(policy);
switch (self.SSLPinningMode) {
case AFSSLPinningModePublicKey: {
NSArray *pinnedPublicKeys = [self.class pinnedPublicKeys];
for (id publicKey in trustChain) {
for (id pinnedPublicKey in pinnedPublicKeys) {
if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)publicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
return;
}
}
}
[[challenge sender] cancelAuthenticationChallenge:challenge];
break;
}
case AFSSLPinningModeCertificate: {
for (id serverCertificateData in trustChain) {
if ([[self.class pinnedCertificates] containsObject:serverCertificateData]) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
return;
}
}
[[challenge sender] cancelAuthenticationChallenge:challenge];
break;
}
case AFSSLPinningModeNone: {
if (self.allowsInvalidSSLCertificate){
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
} else {
SecTrustResultType result = 0;
OSStatus status = SecTrustEvaluate(serverTrust, &result);
NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
if (status == errSecSuccess && (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed)) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
break;
}
}
} else {
if ([challenge previousFailureCount] == 0) {
if (self.credential) {
[[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
} else {
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection {
return self.shouldUseCredentialStorage;
}
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse
{
if (self.redirectResponse) {
return self.redirectResponse(connection, request, redirectResponse);
} else {
return request;
}
}
- (void)connection:(NSURLConnection __unused *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
if (self.uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
});
}
}
- (void)connection:(NSURLConnection __unused *)connection
didReceiveResponse:(NSURLResponse *)response
{
self.response = response;
[self.outputStream open];
}
- (void)connection:(NSURLConnection __unused *)connection
didReceiveData:(NSData *)data
{
NSUInteger length = [data length];
while (YES) {
NSUInteger totalNumberOfBytesWritten = 0;
if ([self.outputStream hasSpaceAvailable]) {
const uint8_t *dataBuffer = (uint8_t *)[data bytes];
NSInteger numberOfBytesWritten = 0;
while (totalNumberOfBytesWritten < length) {
numberOfBytesWritten = [self.outputStream write:&dataBuffer[0] maxLength:length];
if (numberOfBytesWritten == -1) {
[self.connection cancel];
[self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError];
return;
} else {
totalNumberOfBytesWritten += numberOfBytesWritten;
}
}
break;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
self.totalBytesRead += length;
if (self.downloadProgress) {
self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength);
}
});
}
- (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection {
self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
[self.outputStream close];
[self finish];
self.connection = nil;
}
- (void)connection:(NSURLConnection __unused *)connection
didFailWithError:(NSError *)error
{
self.error = error;
[self.outputStream close];
[self finish];
self.connection = nil;
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
if (self.cacheResponse) {
return self.cacheResponse(connection, cachedResponse);
} else {
if ([self isCancelled]) {
return nil;
}
return cachedResponse;
}
}
#pragma mark - NSCoding
- (id)initWithCoder:(NSCoder *)aDecoder {
NSURLRequest *request = [aDecoder decodeObjectForKey:@"request"];
self = [self initWithRequest:request];
if (!self) {
return nil;
}
self.state = (AFOperationState)[aDecoder decodeIntegerForKey:@"state"];
self.cancelled = [aDecoder decodeBoolForKey:@"isCancelled"];
self.response = [aDecoder decodeObjectForKey:@"response"];
self.error = [aDecoder decodeObjectForKey:@"error"];
self.responseData = [aDecoder decodeObjectForKey:@"responseData"];
self.totalBytesRead = [[aDecoder decodeObjectForKey:@"totalBytesRead"] longLongValue];
self.allowsInvalidSSLCertificate = [[aDecoder decodeObjectForKey:@"allowsInvalidSSLCertificate"] boolValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[self pause];
[aCoder encodeObject:self.request forKey:@"request"];
switch (self.state) {
case AFOperationExecutingState:
case AFOperationPausedState:
[aCoder encodeInteger:AFOperationReadyState forKey:@"state"];
break;
default:
[aCoder encodeInteger:self.state forKey:@"state"];
break;
}
[aCoder encodeBool:[self isCancelled] forKey:@"isCancelled"];
[aCoder encodeObject:self.response forKey:@"response"];
[aCoder encodeObject:self.error forKey:@"error"];
[aCoder encodeObject:self.responseData forKey:@"responseData"];
[aCoder encodeObject:[NSNumber numberWithLongLong:self.totalBytesRead] forKey:@"totalBytesRead"];
[aCoder encodeObject:[NSNumber numberWithBool:self.allowsInvalidSSLCertificate] forKey:@"allowsInvalidSSLCertificate"];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request];
operation.uploadProgress = self.uploadProgress;
operation.downloadProgress = self.downloadProgress;
operation.authenticationChallenge = self.authenticationChallenge;
operation.cacheResponse = self.cacheResponse;
operation.redirectResponse = self.redirectResponse;
operation.allowsInvalidSSLCertificate = self.allowsInvalidSSLCertificate;
return operation;
}
@end

View File

@ -0,0 +1,89 @@
// AFXMLRequestOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
#import <Availability.h>
/**
`AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with XML response data.
## Acceptable Content Types
By default, `AFXMLRequestOperation` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
- `application/xml`
- `text/xml`
## Use With AFHTTPClient
When `AFXMLRequestOperation` is registered with `AFHTTPClient`, the response object in the success callback of `HTTPRequestOperationWithRequest:success:failure:` will be an instance of `NSXMLParser`. On platforms that support `NSXMLDocument`, you have the option to ignore the response object, and simply use the `responseXMLDocument` property of the operation argument of the callback.
*/
@interface AFXMLRequestOperation : AFHTTPRequestOperation
///----------------------------
/// @name Getting Response Data
///----------------------------
/**
An `NSXMLParser` object constructed from the response data.
*/
@property (readonly, nonatomic, strong) NSXMLParser *responseXMLParser;
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
/**
An `NSXMLDocument` object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error.
*/
@property (readonly, nonatomic, strong) NSXMLDocument *responseXMLDocument;
#endif
/**
Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML parser constructed with the response data of request.
@param failure A block object to be executed when the operation finishes unsuccessfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network error that occurred.
@return A new XML request operation
*/
+ (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure;
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
/**
Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML document created from the response data of request.
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as XML. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
@return A new XML request operation
*/
+ (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure;
#endif
@end

View File

@ -0,0 +1,167 @@
// AFXMLRequestOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFXMLRequestOperation.h"
#include <Availability.h>
static dispatch_queue_t xml_request_operation_processing_queue() {
static dispatch_queue_t af_xml_request_operation_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", DISPATCH_QUEUE_CONCURRENT);
});
return af_xml_request_operation_processing_queue;
}
@interface AFXMLRequestOperation ()
@property (readwrite, nonatomic, strong) NSXMLParser *responseXMLParser;
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
@property (readwrite, nonatomic, strong) NSXMLDocument *responseXMLDocument;
#endif
@property (readwrite, nonatomic, strong) NSError *XMLError;
@end
@implementation AFXMLRequestOperation
@synthesize responseXMLParser = _responseXMLParser;
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
@synthesize responseXMLDocument = _responseXMLDocument;
#endif
@synthesize XMLError = _XMLError;
+ (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure
{
AFXMLRequestOperation *requestOperation = [(AFXMLRequestOperation *)[self alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success(operation.request, operation.response, responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(operation.request, operation.response, error, [(AFXMLRequestOperation *)operation responseXMLParser]);
}
}];
return requestOperation;
}
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
+ (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure
{
AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, __unused id responseObject) {
if (success) {
NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument];
success(operation.request, operation.response, XMLDocument);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument];
failure(operation.request, operation.response, error, XMLDocument);
}
}];
return requestOperation;
}
#endif
- (NSXMLParser *)responseXMLParser {
if (!_responseXMLParser && [self.responseData length] > 0 && [self isFinished]) {
self.responseXMLParser = [[NSXMLParser alloc] initWithData:self.responseData];
}
return _responseXMLParser;
}
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
- (NSXMLDocument *)responseXMLDocument {
if (!_responseXMLDocument && [self.responseData length] > 0 && [self isFinished]) {
NSError *error = nil;
self.responseXMLDocument = [[NSXMLDocument alloc] initWithData:self.responseData options:0 error:&error];
self.XMLError = error;
}
return _responseXMLDocument;
}
#endif
- (NSError *)error {
if (_XMLError) {
return _XMLError;
} else {
return [super error];
}
}
#pragma mark - NSOperation
- (void)cancel {
[super cancel];
self.responseXMLParser.delegate = nil;
}
#pragma mark - AFHTTPRequestOperation
+ (NSSet *)acceptableContentTypes {
return [NSSet setWithObjects:@"application/xml", @"text/xml", nil];
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[[request URL] pathExtension] isEqualToString:@"xml"] || [super canProcessRequest:request];
}
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
self.completionBlock = ^ {
dispatch_async(xml_request_operation_processing_queue(), ^(void) {
NSXMLParser *XMLParser = self.responseXMLParser;
if (self.error) {
if (failure) {
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
success(self, XMLParser);
});
}
}
});
};
#pragma clang diagnostic pop
}
@end

View File

@ -0,0 +1,78 @@
// UIImageView+AFNetworking.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFImageRequestOperation.h"
#import <Availability.h>
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <UIKit/UIKit.h>
/**
This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL.
*/
@interface UIImageView (AFNetworking)
/**
Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL, and sets it the request is finished. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
@param url The URL used for the image request.
*/
- (void)setImageWithURL:(NSURL *)url;
/**
Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
@param url The URL used for the image request.
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
*/
- (void)setImageWithURL:(NSURL *)url
placeholderImage:(UIImage *)placeholderImage;
/**
Creates and enqueues an image request operation, which asynchronously downloads the image with the specified URL request object. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is executed.
@param urlRequest The URL request used for the image request.
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
@param success A block to be executed when the image request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the request and response parameters will be `nil`.
@param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
*/
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
/**
Cancels any executing image request operation for the receiver, if one exists.
*/
- (void)cancelImageRequestOperation;
@end
#endif

View File

@ -0,0 +1,191 @@
// UIImageView+AFNetworking.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import "UIImageView+AFNetworking.h"
@interface AFImageCache : NSCache
- (UIImage *)cachedImageForRequest:(NSURLRequest *)request;
- (void)cacheImage:(UIImage *)image
forRequest:(NSURLRequest *)request;
@end
#pragma mark -
static char kAFImageRequestOperationObjectKey;
@interface UIImageView (_AFNetworking)
@property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFImageRequestOperation *af_imageRequestOperation;
@end
@implementation UIImageView (_AFNetworking)
@dynamic af_imageRequestOperation;
@end
#pragma mark -
@implementation UIImageView (AFNetworking)
- (AFHTTPRequestOperation *)af_imageRequestOperation {
return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationObjectKey);
}
- (void)af_setImageRequestOperation:(AFImageRequestOperation *)imageRequestOperation {
objc_setAssociatedObject(self, &kAFImageRequestOperationObjectKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
+ (NSOperationQueue *)af_sharedImageRequestOperationQueue {
static NSOperationQueue *_af_imageRequestOperationQueue = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_af_imageRequestOperationQueue = [[NSOperationQueue alloc] init];
[_af_imageRequestOperationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
});
return _af_imageRequestOperationQueue;
}
+ (AFImageCache *)af_sharedImageCache {
static AFImageCache *_af_imageCache = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_af_imageCache = [[AFImageCache alloc] init];
});
return _af_imageCache;
}
#pragma mark -
- (void)setImageWithURL:(NSURL *)url {
[self setImageWithURL:url placeholderImage:nil];
}
- (void)setImageWithURL:(NSURL *)url
placeholderImage:(UIImage *)placeholderImage
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
[self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
}
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
[self cancelImageRequestOperation];
UIImage *cachedImage = [[[self class] af_sharedImageCache] cachedImageForRequest:urlRequest];
if (cachedImage) {
self.af_imageRequestOperation = nil;
if (success) {
success(nil, nil, cachedImage);
} else {
self.image = cachedImage;
}
} else {
if (placeholderImage) {
self.image = placeholderImage;
}
AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest];
#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
requestOperation.allowsInvalidSSLCertificate = YES;
#endif
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) {
if (self.af_imageRequestOperation == operation) {
self.af_imageRequestOperation = nil;
}
if (success) {
success(operation.request, operation.response, responseObject);
} else if (responseObject) {
self.image = responseObject;
}
}
[[[self class] af_sharedImageCache] cacheImage:responseObject forRequest:urlRequest];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) {
if (self.af_imageRequestOperation == operation) {
self.af_imageRequestOperation = nil;
}
if (failure) {
failure(operation.request, operation.response, error);
}
}
}];
self.af_imageRequestOperation = requestOperation;
[[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation];
}
}
- (void)cancelImageRequestOperation {
[self.af_imageRequestOperation cancel];
self.af_imageRequestOperation = nil;
}
@end
#pragma mark -
static inline NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) {
return [[request URL] absoluteString];
}
@implementation AFImageCache
- (UIImage *)cachedImageForRequest:(NSURLRequest *)request {
switch ([request cachePolicy]) {
case NSURLRequestReloadIgnoringCacheData:
case NSURLRequestReloadIgnoringLocalAndRemoteCacheData:
return nil;
default:
break;
}
return [self objectForKey:AFImageCacheKeyFromURLRequest(request)];
}
- (void)cacheImage:(UIImage *)image
forRequest:(NSURLRequest *)request
{
if (image && request) {
[self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)];
}
}
@end
#endif

View File

@ -0,0 +1,19 @@
Copyright (c) 2011 Gowalla (http://gowalla.com/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,208 @@
<p align="center" >
<img src="https://raw.github.com/AFNetworking/AFNetworking/assets/afnetworking-logo.png" alt="AFNetworking" title="AFNetworking">
</p>
[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.png?branch=master)](https://travis-ci.org/AFNetworking/AFNetworking)
AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of [NSURLConnection](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html), [NSOperation](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html), and other familiar Foundation technologies. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. For example, here's how easy it is to get JSON from a URL:
```objective-c
NSURL *url = [NSURL URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"App.net Global Stream: %@", JSON);
} failure:nil];
[operation start];
```
Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac.
Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did!
## How To Get Started
- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/zipball/master) and try out the included Mac and iPhone example apps
- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles in the wiki](https://github.com/AFNetworking/AFNetworking/wiki)
- Check out the [complete documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at the APIs available in AFNetworking
- Watch the [NSScreencast episode about AFNetworking](http://nsscreencast.com/episodes/6-afnetworking) for a quick introduction to how to use it in your application
- Questions? [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking) is the best place to find answers
## Overview
AFNetworking is architected to be as small and modular as possible, in order to make it simple to use and extend.
<table>
<tr><th colspan="2" style="text-align:center;">Core</th></tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFURLConnectionOperation.html">AFURLConnectionOperation</a></td>
<td>An <tt>NSOperation</tt> that implements the <tt>NSURLConnection</tt> delegate methods.</td>
</tr>
<tr><th colspan="2" style="text-align:center;">HTTP Requests</th></tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFHTTPRequestOperation.html">AFHTTPRequestOperation</a></td>
<td>A subclass of <tt>AFURLConnectionOperation</tt> for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.</td>
</tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFJSONRequestOperation.html">AFJSONRequestOperation</a></td>
<td>A subclass of <tt>AFHTTPRequestOperation</tt> for downloading and working with JSON response data.</td>
</tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFXMLRequestOperation.html">AFXMLRequestOperation</a></td>
<td>A subclass of <tt>AFHTTPRequestOperation</tt> for downloading and working with XML response data.</td>
</tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFPropertyListRequestOperation.html">AFPropertyListRequestOperation</a></td>
<td>A subclass of <tt>AFHTTPRequestOperation</tt> for downloading and deserializing objects with <a href="http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/index.html">property list</a> response data.</td>
</tr>
<tr><th colspan="2" style="text-align:center;">HTTP Client</th></tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFHTTPClient.html">AFHTTPClient</a></td>
<td>
Captures the common patterns of communicating with an web application over HTTP, including:
<ul>
<li>Making requests from relative paths of a base URL</li>
<li>Setting HTTP headers to be added automatically to requests</li>
<li>Authenticating requests with HTTP Basic credentials or an OAuth token</li>
<li>Managing an <tt>NSOperationQueue</tt> for requests made by the client</li>
<li>Generating query strings or HTTP bodies from an <tt>NSDictionary</tt></li>
<li>Constructing multipart form requests</li>
<li>Automatically parsing HTTP response data into its corresponding object representation</li>
<li>Monitoring and responding to changes in network reachability</li>
</ul>
</td>
</tr>
<tr><th colspan="2" style="text-align:center;">Images</th></tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFImageRequestOperation.html">AFImageRequestOperation</a></td>
<td>A subclass of <tt>AFHTTPRequestOperation</tt> for downloading and processing images.</td>
</tr>
<tr>
<td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Categories/UIImageView+AFNetworking.html">UIImageView+AFNetworking</a></td>
<td>Adds methods to <tt>UIImageView</tt> for loading remote images asynchronously from a URL.</td>
</tr>
</table>
## Example Usage
### XML Request
```objective-c
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792%40N01&format=rest"]];
AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = self;
[XMLParser parse];
} failure:nil];
[operation start];
```
### Image Request
```objective-c
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
```
### API Client Request
```objective-c
// AFAppDotNetAPIClient is a subclass of AFHTTPClient, which defines the base URL and default HTTP headers for NSURLRequests it creates
[[AFAppDotNetAPIClient sharedClient] getPath:@"stream/0/posts/stream/global" parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
NSLog(@"App.net Global Stream: %@", JSON);
} failure:nil];
```
### File Upload with Progress Callback
```objective-c
NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];
```
### Streaming Request
```objective-c
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];
operation.outputStream = [NSOutputStream outputStreamToMemory];
[operation start];
```
## Requirements
AFNetworking 1.0 and higher requires either [iOS 5.0](http://developer.apple.com/library/ios/#releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS4.html) and above, or [Mac OS 10.7](http://developer.apple.com/library/mac/#releasenotes/MacOSX/WhatsNewInOSX/Articles/MacOSX10_6.html#//apple_ref/doc/uid/TP40008898-SW7) ([64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)) and above.
For compatibility with iOS 4.3, use the latest 0.10.x release.
### ARC
AFNetworking uses ARC as of its 1.0 release.
If you are using AFNetworking 1.0 in your non-arc project, you will need to set a `-fobjc-arc` compiler flag on all of the AFNetworking source files. Conversely, if you are adding a pre-1.0 version of AFNetworking, you will need to set a `-fno-objc-arc` compiler flag.
To set a compiler flag in Xcode, go to your active target and select the "Build Phases" tab. Now select all AFNetworking source files, press Enter, insert `-fobjc-arc` or `-fno-objc-arc` and then "Done" to enable or disable ARC for AFNetworking.
## Unit Tests
AFNetworking includes a suite of unit tests within the Tests subdirectory. In order to run the unit tests, you must install the testing dependencies via CocoaPods. To do so:
$ gem install cocoapods # If necessary
$ cd Tests
$ pod install
Once CocoaPods has finished the installation, you can execute the test suite via the 'iOS Tests' and 'OS X Tests' schemes within Xcode.
### Test Logging
By default, the unit tests do not emit any output during execution. For debugging purposes, it can be useful to enable logging of the requests and responses. Logging support is provided by the [AFHTTPRequestOperationLogger](https://github.com/AFNetworking/AFHTTPRequestOperationLogger) extension, which is installed via CocoaPods into the test targets. To enable logging, edit the test Scheme and add an environment variable named `AFTestsLoggingEnabled` with a value of `YES`.
### Using xctool
If you wish to execute the tests from the command line or within a continuous integration environment, you will need to install [xctool](https://github.com/facebook/xctool). The recommended installation method is [Homebrew](http://mxcl.github.io/homebrew/).
To install the commandline testing support via Homebrew:
$ brew update
$ brew install xctool --HEAD
Once xctool is installed, you can execute the suite via `rake test`.
## Credits
AFNetworking was created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla).
AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/).
And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors).
## Contact
Follow AFNetworking on Twitter ([@AFNetworking](https://twitter.com/AFNetworking))
### Creators
[Mattt Thompson](http://github.com/mattt)
[@mattt](https://twitter.com/mattt)
[Scott Raymond](http://github.com/sco)
[@sco](https://twitter.com/sco)
## License
AFNetworking is available under the MIT license. See the LICENSE file for more info.

View File

@ -0,0 +1 @@
../../AFNetworking/AFNetworking/AFHTTPClient.h

View File

@ -0,0 +1 @@
../../AFNetworking/AFNetworking/AFHTTPRequestOperation.h

View File

@ -0,0 +1 @@
../../AFNetworking/AFNetworking/AFImageRequestOperation.h

View File

@ -0,0 +1 @@
../../AFNetworking/AFNetworking/AFJSONRequestOperation.h

View File

@ -0,0 +1 @@
../../AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h

View File

@ -0,0 +1 @@
../../AFNetworking/AFNetworking/AFNetworking.h

View File

@ -0,0 +1 @@
../../AFNetworking/AFNetworking/AFPropertyListRequestOperation.h

View File

@ -0,0 +1 @@
../../AFNetworking/AFNetworking/AFURLConnectionOperation.h

View File

@ -0,0 +1 @@
../../AFNetworking/AFNetworking/AFXMLRequestOperation.h

View File

@ -0,0 +1 @@
../../AFNetworking/AFNetworking/UIImageView+AFNetworking.h

View File

@ -0,0 +1 @@
../../AFNetworking/AFNetworking/AFHTTPClient.h

Some files were not shown because too many files have changed in this diff Show More