You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Swift项目中配置Amplify对接已有AppSync(MySQL)API?

配置已有AppSync API到Swift Amplify项目

一、导入已有AppSync资源到Amplify项目

Amplify CLI支持导入已有的AppSync API,步骤如下:

  • 在Swift项目的Amplify初始化目录下,执行命令:
    amplify import api
    
  • 按照CLI提示选择GraphQL类型,接着选AppSync,输入你的AppSync API ID(可在AppSync控制台的「设置」页找到)。
  • CLI会自动拉取API的Schema和配置,生成amplify/backend/api/[API名称]目录,并更新amplifyconfiguration.json配置文件。

如果CLI导入失败,可手动修改amplifyconfiguration.json:

  • 从AppSync控制台复制API端点、地域、认证信息(如API密钥、Cognito配置等)。
  • 替换或添加awsAPIPlugin配置段,示例:
    {
      "UserAgent": "aws-amplify-cli/2.0",
      "Version": "1.0",
      "awsAPIPlugin": {
        "MyExistingAppSyncAPI": {
          "endpointType": "GraphQL",
          "endpoint": "https://xxx.appsync-api.us-east-1.amazonaws.com/graphql",
          "region": "us-east-1",
          "authorizationType": "API_KEY",
          "apiKey": "da2-xxxxxxxxxxxxxxxxxxxxxxxxxx"
        }
      }
    }
    
    注意根据你的AppSync认证方式(IAM/Cognito/OAuth)调整authorizationType和对应配置项。

二、Swift代码中配置与使用API

1. 导入依赖库

确保项目已通过Swift Package Manager或CocoaPods安装Amplify和AWSAPIPlugin(若用Cognito认证,需额外安装AWSCognitoAuthPlugin):

import Amplify
import AWSAPIPlugin

2. 初始化Amplify

在App启动入口(如AppDelegate、SceneDelegate或SwiftUI的App结构体)中配置Amplify:

do {
    try Amplify.add(plugin: AWSAPIPlugin())
    // 若使用Cognito认证,添加try Amplify.add(plugin: AWSCognitoAuthPlugin())
    try Amplify.configure()
    print("Amplify 配置成功")
} catch {
    print("Amplify 配置失败: \(error)")
}

3. 执行GraphQL操作

基础查询示例

假设Schema中有getPost查询:

let queryRequest = GraphQLRequest<Post>(
    document: """
    query GetPost($id: ID!) {
        getPost(id: $id) {
            id
            title
            content
        }
    }
    """,
    variables: ["id": "123"]
)

Amplify.API.query(request: queryRequest) { result in
    switch result {
    case .success(let response):
        if let post = response.data {
            print("获取到文章: \(post.title)")
        } else if let errors = response.errors {
            print("查询错误: \(errors)")
        }
    case .failure(let error):
        print("查询失败: \(error)")
    }
}

变更操作示例

以创建文章为例:

let mutationRequest = GraphQLRequest<Post>(
    document: """
    mutation CreatePost($input: CreatePostInput!) {
        createPost(input: $input) {
            id
            title
            content
        }
    }
    """,
    variables: ["input": ["title": "新文章", "content": "Amplify接入测试"]]
)

Amplify.API.mutate(request: mutationRequest) { result in
    switch result {
    case .success(let response):
        if let post = response.data {
            print("创建文章成功,ID: \(post.id)")
        } else if let errors = response.errors {
            print("变更错误: \(errors)")
        }
    case .failure(let error):
        print("变更失败: \(error)")
    }
}

类型安全操作(可选)

用Amplify Codegen生成模型类,实现类型化调用:

  • 执行命令生成模型:
    amplify codegen models
    
  • 之后可直接使用生成的查询/变更类:
    let getPostQuery = GetPostQuery(id: "123")
    Amplify.API.query(request: getPostQuery) { result in
        // 处理结果逻辑
    }
    

三、注意事项

  • 确保amplifyconfiguration.json已添加到Xcode目标的「Copy Bundle Resources」中。
  • 认证方式必须与AppSync API的配置完全匹配,否则会出现权限错误。
  • 若项目已有其他API资源,导入时需保证API名称不冲突,或在代码中指定目标API名称。

内容的提问来源于stack exchange,提问作者D.Schall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 09:35:18