Use iOS SDK generated by API Gateway for a REST API in Objective-C or Swift
In this tutorial, we will show how to use an iOS SDK generated by API Gateway for a REST API in an Objective-C or Swift app to call the underlying API. We will use the SimpleCalc API as an example to illustrate the following topics:
-
How to install the required AWS Mobile SDK components into your Xcode project
-
How to create the API client object before calling the API's methods
-
How to call the API methods through the corresponding SDK methods on the API client object
-
How to prepare a method input and parse its result using the corresponding model classes of the SDK
Use generated iOS SDK (Objective-C) to call API
Before beginning the following procedure, you must complete the steps in Generate SDKs for REST APIs in API Gateway for iOS in Objective-C and download the .zip file of the generated SDK.
Install the AWS mobile SDK and an iOS SDK generated by API Gateway in an Objective-C project
The following procedure describes how to install the SDK.
To install and use an iOS SDK generated by API Gateway in Objective-C
-
Extract the contents of the API Gateway-generated .zip file you downloaded earlier. Using the SimpleCalc API, you may want to rename the unzipped SDK folder to something like
sdk_objc_simple_calc
. In this SDK folder there is aREADME.md
file and aPodfile
file. TheREADME.md
file contains the instructions to install and use the SDK. This tutorial provides details about these instructions. The installation leverages CocoaPodsto import required API Gateway libraries and other dependent AWS Mobile SDK components. You must update the Podfile
to import the SDKs into your app's Xcode project. The unarchived SDK folder also contains agenerated-src
folder that contains the source code of the generated SDK of your API. -
Launch Xcode and create a new iOS Objective-C project. Make a note of the project's target. You will need to set it in the
Podfile
. -
To import the AWS Mobile SDK for iOS into the Xcode project by using CocoaPods, do the following:
-
Install CocoaPods by running the following command in a terminal window:
sudo gem install cocoapods pod setup
-
Copy the
Podfile
file from the extracted SDK folder into the same directory containing your Xcode project file. Replace the following block:target '
<YourXcodeTarget>
' do pod 'AWSAPIGateway', '~> 2.4.7' endwith your project's target name:
target '
app_objc_simple_calc
' do pod 'AWSAPIGateway', '~> 2.4.7' endIf your Xcode project already contains a file named
Podfile
, add the following line of code to it:pod 'AWSAPIGateway', '~> 2.4.7'
-
Open a terminal window and run the following command:
pod install
This installs the API Gateway component and other dependent AWS Mobile SDK components.
-
Close the Xcode project and then open the
.xcworkspace
file to relaunch Xcode. -
Add all of the
.h
and.m
files from the extracted SDK'sgenerated-src
directory into your Xcode project.
To import the AWS Mobile SDK for iOS Objective-C into your project by explicitly downloading AWS Mobile SDK or using Carthage
, follow the instructions in the README.md file. Be sure to use only one of these options to import the AWS Mobile SDK. -
Call API methods using the iOS SDK generated by API Gateway in an Objective-C project
When you generated the SDK with the prefix of SIMPLE_CALC
for this SimpleCalc API with two models for input
(Input
) and output (Result
) of the methods, in the SDK,
the resulting API client class becomes SIMPLE_CALCSimpleCalcClient
and the
corresponding data classes are SIMPLE_CALCInput
and
SIMPLE_CALCResult
, respectively. The API requests and responses are
mapped to the SDK methods as follows:
-
The API request of
GET /?a=...&b=...&op=...
becomes the SDK method of
(AWSTask *)rootGet:(NSString *)op a:(NSString *)a b:(NSString *)b
The
AWSTask.result
property is of theSIMPLE_CALCResult
type if theResult
model was added to the method response. Otherwise, the property is of theNSDictionary
type. -
This API request of
POST / { "a": "Number", "b": "Number", "op": "String" }
becomes the SDK method of
(AWSTask *)rootPost:(SIMPLE_CALCInput *)body
-
The API request of
GET /{a}/{b}/{op}
becomes the SDK method of
(AWSTask *)aBOpGet:(NSString *)a b:(NSString *)b op:(NSString *)op
The following procedure describes how to call the API methods in Objective-C app
source code; for example, as part of the viewDidLoad
delegate in a
ViewController.m
file.
To call the API through the iOS SDK generated by API Gateway
-
Import the API client class header file to make the API client class callable in the app:
#import "SIMPLE_CALCSimpleCalc.h"
The
#import
statement also importsSIMPLE_CALCInput.h
andSIMPLE_CALCResult.h
for the two model classes. -
Instantiate the API client class:
SIMPLE_CALCSimpleCalcClient *apiInstance = [SIMPLE_CALCSimpleCalcClient defaultClient];
To use Amazon Cognito with the API, set the
defaultServiceConfiguration
property on the defaultAWSServiceManager
object, as shown in the following, before calling thedefaultClient
method to create the API client object (shown in the preceding example):AWSCognitoCredentialsProvider *creds = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:
AWSRegionUSEast1
identityPoolId:your_cognito_pool_id
]; AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1
credentialsProvider:creds]; AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration; -
Call the
GET /?a=1&b=2&op=+
method to perform1+2
:[[apiInstance rootGet: @"+" a:@"1" b:@"2"] continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) { _textField1.text = [self handleApiResponse:task]; return nil; }];
where the helper function
handleApiResponse:task
formats the result as a string to be displayed in a text field (_textField1
).- (NSString *)handleApiResponse:(AWSTask *)task { if (task.error != nil) { return [NSString stringWithFormat: @"Error: %@", task.error.description]; } else if (task.result != nil && [task.result isKindOfClass:[SIMPLE_CALCResult class]]) { return [NSString stringWithFormat:@"%@ %@ %@ = %@\n",task.result.input.a, task.result.input.op, task.result.input.b, task.result.output.c]; } return nil; }
The resulting display is
1 + 2 = 3
. -
Call the
POST /
with a payload to perform1-2
:SIMPLE_CALCInput *input = [[SIMPLE_CALCInput alloc] init]; input.a = [NSNumber numberWithInt:1]; input.b = [NSNumber numberWithInt:2]; input.op = @"-"; [[apiInstance rootPost:input] continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) { _textField2.text = [self handleApiResponse:task]; return nil; }];
The resulting display is
1 - 2 = -1
. -
Call the
GET /{a}/{b}/{op}
to perform1/2
:[[apiInstance aBOpGet:@"1" b:@"2" op:@"div"] continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) { _textField3.text = [self handleApiResponse:task]; return nil; }];
The resulting display is
1 div 2 = 0.5
. Here,div
is used in place of/
because the simple Lambda function in the backend does not handle URL encoded path variables.
Use generated iOS SDK (Swift) to call API
Before beginning the following procedure, you must complete the steps in Generate SDKs for REST APIs in API Gateway for iOS in Swift and download the .zip file of the generated SDK.
Topics
Install AWS mobile SDK and API Gateway-generated SDK in a Swift project
The following procedure describes how to install the SDK.
To install and use an iOS SDK generated by API Gateway in Swift
-
Extract the contents of the API Gateway-generated .zip file you downloaded earlier. Using the SimpleCalc API, you may want to rename the unzipped SDK folder to something like
sdk_swift_simple_calc
. In this SDK folder there is aREADME.md
file and aPodfile
file. TheREADME.md
file contains the instructions to install and use the SDK. This tutorial provides details about these instructions. The installation leverages CocoaPodsto import required AWS Mobile SDK components. You must update the Podfile
to import the SDKs into your Swift app's Xcode project. The unarchived SDK folder also contains agenerated-src
folder that contains the source code of the generated SDK of your API. -
Launch Xcode and create a new iOS Swift project. Make a note of the project's target. You will need to set it in the
Podfile
. -
To import the required AWS Mobile SDK components into the Xcode project by using CocoaPods, do the following:
-
If it is not installed, install CocoaPods by running the following command in a terminal window:
sudo gem install cocoapods pod setup
-
Copy the
Podfile
file from the extracted SDK folder into the same directory containing your Xcode project file. Replace the following block:target '
<YourXcodeTarget>
' do pod 'AWSAPIGateway', '~> 2.4.7' endwith your project's target name as shown:
target '
app_swift_simple_calc
' do pod 'AWSAPIGateway', '~> 2.4.7' endIf your Xcode project already contains a
Podfile
with the correct target, you can simply add the following line of code to thedo ... end
loop:pod 'AWSAPIGateway', '~> 2.4.7'
-
Open a terminal window and run the following command in the app directory:
pod install
This installs the API Gateway component and any dependent AWS Mobile SDK components into the app's project.
-
Close the Xcode project and then open the
*.xcworkspace
file to relaunch Xcode. -
Add all of the SDK's header files (
.h
) and Swift source code files (.swift
) from the extractedgenerated-src
directory to your Xcode project. -
To enable calling the Objective-C libraries of the AWS Mobile SDK from your Swift code project, set the
Bridging_Header.h
file path on the Objective-C Bridging Header property under the Swift Compiler - General setting of your Xcode project configuration:Tip
You can type
bridging
in the search box of Xcode to locate the Objective-C Bridging Header property. -
Build the Xcode project to verify that it is properly configured before proceeding further. If your Xcode uses a more recent version of Swift than the one supported for the AWS Mobile SDK, you will get Swift compiler errors. In this case, set the Use Legacy Swift Language Version property to Yes under the Swift Compiler - Version setting:
To import the AWS Mobile SDK for iOS in Swift into your project by explicitly downloading the AWS Mobile SDK or using Carthage
, follow the instructions in the README.md
file that comes with the SDK package. Be sure to use only one of these options to import the AWS Mobile SDK. -
Call API methods through the iOS SDK generated by API Gateway in a Swift project
When you generated the SDK with the prefix of SIMPLE_CALC
for this
SimpleCalc API with two models to
describe the input (Input
) and output (Result
) of the API's
requests and responses, in the SDK, the resulting API client class becomes
SIMPLE_CALCSimpleCalcClient
and the corresponding data classes are
SIMPLE_CALCInput
and SIMPLE_CALCResult
, respectively. The
API requests and responses are mapped to the SDK methods as follows:
-
The API request of
GET /?a=...&b=...&op=...
becomes the SDK method of
public func rootGet(op: String?, a: String?, b: String?) -> AWSTask
The
AWSTask.result
property is of theSIMPLE_CALCResult
type if theResult
model was added to the method response. Otherwise, it is of theNSDictionary
type. -
This API request of
POST / { "a": "Number", "b": "Number", "op": "String" }
becomes the SDK method of
public func rootPost(body: SIMPLE_CALCInput) -> AWSTask
-
The API request of
GET /{a}/{b}/{op}
becomes the SDK method of
public func aBOpGet(a: String, b: String, op: String) -> AWSTask
The following procedure describes how to call the API methods in Swift app source
code; for example, as part of the viewDidLoad()
delegate in a
ViewController.m
file.
To call the API through the iOS SDK generated by API Gateway
-
Instantiate the API client class:
let client = SIMPLE_CALCSimpleCalcClient.default()
To use Amazon Cognito with the API, set a default AWS service configuration (shown following) before getting the
default
method (shown previously):let credentialsProvider = AWSCognitoCredentialsProvider(regionType:
AWSRegionType.USEast1
, identityPoolId: "my_pool_id
") let configuration = AWSServiceConfiguration(region:AWSRegionType.USEast1
, credentialsProvider: credentialsProvider) AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration -
Call the
GET /?a=1&b=2&op=+
method to perform1+2
:client.rootGet("+", a: "1", b:"2").continueWithBlock {(task: AWSTask) -> AnyObject? in self.showResult(task) return nil }
where the helper function
self.showResult(task)
prints the result or error to the console; for example:func showResult(task: AWSTask) { if let error = task.error { print("Error: \(error)") } else if let result = task.result { if result is SIMPLE_CALCResult { let res = result as! SIMPLE_CALCResult print(String(format:"%@ %@ %@ = %@", res.input!.a!, res.input!.op!, res.input!.b!, res.output!.c!)) } else if result is NSDictionary { let res = result as! NSDictionary print("NSDictionary: \(res)") } } }
In a production app, you can display the result or error in a text field. The resulting display is
1 + 2 = 3
. -
Call the
POST /
with a payload to perform1-2
:let body = SIMPLE_CALCInput() body.a=1 body.b=2 body.op="-" client.rootPost(body).continueWithBlock {(task: AWSTask) -> AnyObject? in self.showResult(task) return nil }
The resultant display is
1 - 2 = -1
. -
Call the
GET /{a}/{b}/{op}
to perform1/2
:client.aBOpGet("1", b:"2", op:"div").continueWithBlock {(task: AWSTask) -> AnyObject? in self.showResult(task) return nil }
The resulting display is
1 div 2 = 0.5
. Here,div
is used in place of/
because the simple Lambda function in the backend does not handle URL encoded path variables.