

# 在 Objective-C 或 Swift 中使用由 API Gateway 为 REST API 生成的 iOS 开发工具包
<a name="how-to-generate-sdk-ios"></a>

在本教程中，我们将介绍如何在 Objective-C 或 Swift 应用程序中使用由 API Gateway 为 REST API 生成的 iOS 开发工具包来调用底层 API。我们将使用 [SimpleCalc API](simple-calc-lambda-api.md) 作为示例来说明以下主题：
+ 如何将所需的 AWS 移动开发工具包组件安装到您的 Xcode 项目中
+ 如何在调用 API 的方法前创建 API 客户端对象
+ 如何通过 API 客户端对象上相应的 SDK 方法调用 API 方法
+ 如何使用 SDK 的相应模型类来准备方法输入并分析其结果

**Topics**
+ [

## 使用生成的 iOS 开发工具包 (Objective-C) 来调用 API
](#how-to-use-sdk-ios-objc)
+ [

## 使用生成的 iOS 开发工具包 (Swift) 来调用 API
](#how-to-generate-sdk-ios-swift)

## 使用生成的 iOS 开发工具包 (Objective-C) 来调用 API
<a name="how-to-use-sdk-ios-objc"></a>

在开始以下过程之前，您必须完成[为 API Gateway 中的 REST API 生成 SDK](how-to-generate-sdk.md)中适用于 Objective-C 版 iOS 的步骤，并下载已生成的软件开发工具包的 .zip 文件。

### 在 Objective-C 项目中安装 AWS 移动开发工具包和 API Gateway 生成的 iOS 开发工具包
<a name="use-sdk-ios-objc-install-sdk"></a>

以下过程将介绍如何安装开发工具包。

**安装并使用 API Gateway 生成的 Objective-C 版 iOS 开发工具包**

1. 提取您之前下载的 API Gateway 生成的 .zip 文件中的内容。使用 [SimpleCalc API](simple-calc-lambda-api.md)，您可能需要将解压的软件开发工具包文件夹重命名为类似 **sdk\$1objc\$1simple\$1calc** 的名字。此开发工具包文件夹中有一个 `README.md` 文件和一个 `Podfile` 文件。`README.md` 文件包含介绍如何安装和使用开发工具包的说明。本教程将提供有关这些说明的详细信息。安装过程会利用 [CocoaPods](https://cocoapods.org) 导入必需的 API Gateway 库和其他依赖的AWS移动开发工具包组件。您必须更新 `Podfile`，才能将开发工具包导入应用程序的 Xcode 项目中。解档开发工具包文件夹还包含一个 `generated-src` 文件夹，其中包含 API 已生成开发工具包的源代码。

1. 启动 Xcode，并创建一个新的 iOS Objective-C 项目。请记下该项目的目标。您需要在 `Podfile` 中对其进行设置。

      
![\[在 Xcode 中找到目标。\]](http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/images/use-sdk-in-ios-objc-project-find-target.png)

1. 要使用 CocoaPods 将 AWS Mobile SDK for iOS 导入 Xcode 项目中，请执行以下操作：

   1. 通过在终端窗口运行以下命令来安装 CocoaPods：

      ```
      sudo gem install cocoapods
      pod setup
      ```

   1. 将 `Podfile` 文件从提取的开发工具包文件夹复制到包含 Xcode 项目文件的同一目录。将以下代码块：

      ```
      target '<YourXcodeTarget>' do
          pod 'AWSAPIGateway', '~> 2.4.7'
      end
      ```

      替换为您的项目的目标名称：

      ```
      target 'app_objc_simple_calc' do
          pod 'AWSAPIGateway', '~> 2.4.7'
      end
      ```

      如果 Xcode 项目已经包含名为 `Podfile` 的文件，请向其添加以下代码行：

      ```
      pod 'AWSAPIGateway', '~> 2.4.7'
      ```

   1. 打开终端窗口，并运行以下命令：

      ```
      pod install
      ```

      这将安装 API Gateway 组件和其他依赖的 AWS 移动开发工具包组件。

   1. 关闭 Xcode 项目，然后打开 `.xcworkspace` 文件，以重新启动 Xcode。

   1. 将已提取开发工具包的 `.h` 目录中的所有 `.m` 和 `generated-src` 文件添加到 Xcode 项目中。

         
![\[.h 和 .m 文件位于 generated-src 中\]](http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/images/use-sdk-in-ios-objc-project-add-sdk-src.png)

   要通过显式下载 AWS Mobile SDK for iOS 移动开发工具包或使用 AWSCarthage[ 的方式将 ](https://github.com/Carthage/Carthage#installing-carthage) Objective-C 导入您的项目中，请遵循 *README.md* 文件中的说明。确保只使用以下选项之一来导入 AWS 移动开发工具包。

### 在 Objective-C 项目中使用 API Gateway 生成的 iOS 开发工具包调用 API 方法
<a name="use-sdk-ios-objc-call-sdk"></a>

当您为此 [SimpleCalc API](simple-calc-lambda-api.md) 生成具有 `SIMPLE_CALC` 前缀的开发工具包，并将两个模型用于方法的输入 (`Input`) 和输出 (`Result`) 时，在开发工具包中，由此产生的 API 客户端类将变成 `SIMPLE_CALCSimpleCalcClient`，而且相应数据类分别是 `SIMPLE_CALCInput` 和 `SIMPLE_CALCResult`。API 请求和响应映射到开发工具包方法，如下所示：
+ 以下 API 请求

  ```
  GET /?a=...&b=...&op=...
  ```

  将变为以下开发工具包方法

  ```
  (AWSTask *)rootGet:(NSString *)op a:(NSString *)a b:(NSString *)b
  ```

  `AWSTask.result` 属性的类型是 `SIMPLE_CALCResult`，前提是 `Result` 模型已添加到该方法响应中。否则，属性的类型将是 `NSDictionary`。
+ 以下 API 请求

  ```
  POST /
      
  {
     "a": "Number",
     "b": "Number",
     "op": "String"
  }
  ```

  将变为以下开发工具包方法

  ```
  (AWSTask *)rootPost:(SIMPLE_CALCInput *)body
  ```
+ 以下 API 请求

  ```
  GET /{a}/{b}/{op}
  ```

  将变为以下开发工具包方法

  ```
  (AWSTask *)aBOpGet:(NSString *)a b:(NSString *)b op:(NSString *)op
  ```

以下过程将介绍如何在 Objective-C 应用程序源代码中调用 API 方法；例如，作为 `viewDidLoad` 文件中 `ViewController.m` 委派的一部分进行调用。

**通过 API Gateway 生成的 iOS 开发工具包调用 API**

1. 导入 API 客户端类标头文件，使 API 客户端类可在该应用程序内调用：

   ```
   #import "SIMPLE_CALCSimpleCalc.h"
   ```

   `#import` 语句还将为两个模型类导入 `SIMPLE_CALCInput.h` 和 `SIMPLE_CALCResult.h`。

1. 实例化 API 客户端类：

   ```
   SIMPLE_CALCSimpleCalcClient *apiInstance = [SIMPLE_CALCSimpleCalcClient defaultClient];
   ```

   要将 Amazon Cognito 和该 API 结合使用，请在默认的 `AWSServiceManager` 对象上设置 `defaultServiceConfiguration` 属性（如下所示），然后再调用 `defaultClient` 方法，以创建 API 客户端对象（如上一示例所示）：

   ```
   AWSCognitoCredentialsProvider *creds = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1 identityPoolId:your_cognito_pool_id];
   AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1 credentialsProvider:creds];
   AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration;
   ```

1. 调用 `GET /?a=1&b=2&op=+` 方法以执行 `1+2`：

   ```
   [[apiInstance rootGet: @"+" a:@"1" b:@"2"] continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) {
       _textField1.text = [self handleApiResponse:task];
       return nil;
   }];
   ```

   其中，帮助程序函数 `handleApiResponse:task` 会将结果格式设定为要在文本字段 (`_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;
   }
   ```

   最终显示为 `1 + 2 = 3`。

1. 使用负载调用 `POST /` 以执行 `1-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;
       }];
   ```

   最终显示为 `1 - 2 = -1`。

1. 调用 `GET /{a}/{b}/{op}` 以执行 `1/2`：

   ```
   [[apiInstance aBOpGet:@"1" b:@"2" op:@"div"] continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) {
       _textField3.text = [self handleApiResponse:task];
       return nil;
   }];
   ```

   最终显示为 `1 div 2 = 0.5`。在这里，`div` 用于代替 `/`，因为后端的[简单 Lambda 函数](simple-calc-nodejs-lambda-function.md)不会处理 URL 编码的路径变量。

## 使用生成的 iOS 开发工具包 (Swift) 来调用 API
<a name="how-to-generate-sdk-ios-swift"></a>

在开始以下过程之前，您必须完成 [为 API Gateway 中的 REST API 生成 SDK](how-to-generate-sdk.md) 中适用于 Swift 版 iOS 的步骤，并下载已生成的开发工具包的 .zip 文件。

**Topics**
+ [

### 在 Swift 项目中安装 AWS 移动开发工具包和 API Gateway 生成的开发工具包
](#use-sdk-ios-swift-install-sdk)
+ [

### 在 Swift 项目中通过 API Gateway 生成的 iOS 开发工具包调用 API 方法
](#use-sdk-ios-swift-call-api)

### 在 Swift 项目中安装 AWS 移动开发工具包和 API Gateway 生成的开发工具包
<a name="use-sdk-ios-swift-install-sdk"></a>

以下过程将介绍如何安装开发工具包。

**安装并使用 API Gateway 生成的 Swift 版 iOS 开发工具包**

1. 提取您之前下载的 API Gateway 生成的 .zip 文件中的内容。使用 [SimpleCalc API](simple-calc-lambda-api.md)，您可能需要将解压的软件开发工具包文件夹重命名为类似 **sdk\$1swift\$1simple\$1calc** 的名字。此开发工具包文件夹中有一个 `README.md` 文件和一个 `Podfile` 文件。`README.md` 文件包含介绍如何安装和使用开发工具包的说明。本教程将提供有关这些说明的详细信息。安装过程会利用 [CocoaPods](https://cocoapods.org) 导入必需的 AWS 移动开发工具包组件。您必须更新 `Podfile`，才能将开发工具包导入 Swift 应用程序的 Xcode 项目中。解档开发工具包文件夹还包含一个 `generated-src` 文件夹，其中包含 API 已生成开发工具包的源代码。

1. 启动 Xcode，并创建一个新的 iOS Swift 项目。请记下该项目的目标。您需要在 `Podfile` 中对其进行设置。

      
![\[在 Xcode 中找到目标。\]](http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/images/use-sdk-in-ios-swift-project-find-target.png)

1. 要使用 CocoaPods 将必需的 AWS 移动开发工具包组件导入 Xcode 项目中，请执行以下操作：

   1. 如果 CocoaPods 还未安装，请在终端窗口中运行以下命令进行安装：

      ```
      sudo gem install cocoapods
      pod setup
      ```

   1. 将 `Podfile` 文件从提取的开发工具包文件夹复制到包含 Xcode 项目文件的同一目录。将以下代码块：

      ```
      target '<YourXcodeTarget>' do
          pod 'AWSAPIGateway', '~> 2.4.7'
      end
      ```

      替换为您的项目的目标名称，如下所示：

      ```
      target 'app_swift_simple_calc' do
          pod 'AWSAPIGateway', '~> 2.4.7'
      end
      ```

      如果 Xcode 项目已经包含带有正确目标的 `Podfile`，您只需将以下代码行添加到 `do ... end` 循环：

      ```
      pod 'AWSAPIGateway', '~> 2.4.7'
      ```

   1. 打开终端窗口，并在应用程序目录中运行以下命令：

      ```
      pod install
      ```

      这会将 API Gateway 组件及任何依赖的 AWS 移动开发工具包组件安装到应用程序的项目中。

   1. 关闭 Xcode 项目，然后打开 `*.xcworkspace` 文件，以重新启动 Xcode。

   1. 将已提取 `.h` 目录中所有开发工具包的标头文件 (`.swift`) 和 Swift 源代码文件 (`generated-src`) 添加到您的 Xcode 项目中。

         
![\[.h 和 .swift 文件位于 generated-src 中\]](http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/images/use-sdk-in-ios-swift-project-add-sdk-src.png)

   1. 为了能够从 Swift 代码项目调用 AWS 移动开发工具包的 Objective-C 库，请在 Xcode 项目配置的 `Bridging_Header.h`Swift Compiler - General** 设置下，在 **Objective-C Bridging Header** 属性上设置 ** 文件路径：

         
![\[在“Swift 编译器 - 通用”下设置 Bridging_Header.h 文件路径。\]](http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/images/use-sdk-in-ios-swift-project-set-bridging-header.png)
**提示**  
您可以通过在 Xcode 的搜索框中键入 **bridging** 来找到 **Objective-C Bridging Header** 属性。

   1. 构建 Xcode 项目，以在继续进行操作之前验证它是否正确配置。如果与 AWS 移动开发工具包支持的 Swift 版本相比，您的 Xcode 使用了更新的版本，那么您将收到 Swift 编译器错误。在这种情况下，在 **Swift Compiler - Version** 设置下方将 **Use Legacy Swift Language Version (使用传统 Swift 语言版本)** 属性设置为**是**：

         
![\[将“旧版 Swift 语言版本”属性设置为“是”。\]](http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/images/use-sdk-in-ios-swift-project-set-legacy-swift-version.png)

   要通过显式下载AWS移动软件开发工具包或使用 [Carthage](https://github.com/Carthage/Carthage#installing-carthage)，将 Swift 中的AWS移动版 SDK for iOS 导入您的项目中，请按照开发工具包随附的 `README.md` 文件中的说明操作。确保只使用以下选项之一来导入 AWS 移动开发工具包。

### 在 Swift 项目中通过 API Gateway 生成的 iOS 开发工具包调用 API 方法
<a name="use-sdk-ios-swift-call-api"></a>

当您为此 [SimpleCalc API](simple-calc-lambda-api.md) 生成具有 `SIMPLE_CALC` 前缀的开发工具包，并通过两个模型描述 API 请求和响应的输入 (`Input`) 和输出 (`Result`) 时，在开发工具包中，由此产生的 API 客户端类将变成 `SIMPLE_CALCSimpleCalcClient`，而且相应数据类分别是 `SIMPLE_CALCInput` 和 `SIMPLE_CALCResult`。API 请求和响应映射到开发工具包方法，如下所示：
+ 以下 API 请求

  ```
  GET /?a=...&b=...&op=...
  ```

  将变为以下开发工具包方法

  ```
  public func rootGet(op: String?, a: String?, b: String?) -> AWSTask
  ```

  `AWSTask.result` 属性的类型是 `SIMPLE_CALCResult`，前提是 `Result` 模型已添加到该方法响应中。否则，它的类型将是 `NSDictionary`。
+ 以下 API 请求

  ```
  POST /
      
  {
     "a": "Number",
     "b": "Number",
     "op": "String"
  }
  ```

  将变为以下开发工具包方法

  ```
  public func rootPost(body: SIMPLE_CALCInput) -> AWSTask
  ```
+ 以下 API 请求

  ```
  GET /{a}/{b}/{op}
  ```

  将变为以下开发工具包方法

  ```
  public func aBOpGet(a: String, b: String, op: String) -> AWSTask
  ```

以下过程将介绍如何在 Swift 应用程序源代码中调用 API 方法；例如，作为 `viewDidLoad()` 文件中 `ViewController.m` 委派的一部分进行调用。

**通过 API Gateway 生成的 iOS 开发工具包调用 API**

1. 实例化 API 客户端类：

   ```
   let client = SIMPLE_CALCSimpleCalcClient.default()
   ```

   要将 Amazon Cognito 与 API 结合使用，请设置默认 AWS 服务配置（如下所示），然后再获取 `default` 方法（如之前所示）：

   ```
   let credentialsProvider = AWSCognitoCredentialsProvider(regionType: AWSRegionType.USEast1, identityPoolId: "my_pool_id")        
   let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)        
   AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration
   ```

1. 调用 `GET /?a=1&b=2&op=+` 方法以执行 `1+2`：

   ```
   client.rootGet("+", a: "1", b:"2").continueWithBlock {(task: AWSTask) -> AnyObject? in
       self.showResult(task)
       return nil
   }
   ```

   其中，帮助程序函数 `self.showResult(task)` 会将结果或错误打印到控制台；例如：

   ```
   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)")
           }
       }
   }
   ```

   在生产应用程序中，您可以在文本字段中显示结果或错误。最终显示为 `1 + 2 = 3`。

1. 使用负载调用 `POST /` 以执行 `1-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
   }
   ```

   结果显示为 `1 - 2 = -1`。

1. 调用 `GET /{a}/{b}/{op}` 以执行 `1/2`：

   ```
   client.aBOpGet("1", b:"2", op:"div").continueWithBlock {(task: AWSTask) -> AnyObject? in
       self.showResult(task)
       return nil
   }
   ```

   最终显示为 `1 div 2 = 0.5`。在这里，`div` 用于代替 `/`，因为后端的[简单 Lambda 函数](simple-calc-nodejs-lambda-function.md)不会处理 URL 编码的路径变量。