如何在Swift(iOS应用)中调用Vertex AI端点?
在Swift iOS应用中调用Vertex AI端点的方法
一、核心结论
可以通过Swift代码直接调用Vertex AI端点,主要有两种实现路径:原生REST API调用、Google Cloud Swift SDK调用,同时需注意身份验证的安全性。
二、具体实现方式
方式1:原生REST API调用(无需额外SDK)
这是最灵活的方式,用iOS原生URLSession即可完成请求。
步骤说明:
身份验证处理
Vertex AI端点要求OAuth 2.0令牌验证,推荐通过Google Sign-In for iOS获取用户授权令牌,避免在客户端硬编码服务账号密钥(会导致安全泄露)。用户登录后,从GIDAuthentication对象中提取accessToken。构造请求与调用
端点URL格式:https://[REGION]-aiplatform.googleapis.com/v1/projects/[PROJECT_ID]/locations/[REGION]/endpoints/[ENDPOINT_ID]:predict
请求体需严格匹配你部署模型的输入格式,比如文本生成模型的请求体示例:{ "instances": [{"content": "你的输入内容"}] }Swift代码示例
import Foundation import GoogleSignIn func callVertexAIEndpoint(input: String, completion: @escaping (Result<String, Error>) -> Void) { guard let currentUser = GIDSignIn.sharedInstance.currentUser, let accessToken = currentUser.authentication.accessToken else { completion(.failure(NSError(domain: "AuthError", code: 0, userInfo: [NSLocalizedDescriptionKey: "用户未完成授权"]))) return } // 替换为你的项目、区域、端点ID let endpointURL = URL(string: "https://us-central1-aiplatform.googleapis.com/v1/projects/你的项目ID/locations/us-central1/endpoints/你的端点ID:predict")! var request = URLRequest(url: endpointURL) request.httpMethod = "POST" request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") request.setValue("application/json", forHTTPHeaderField: "Content-Type") // 根据模型输入格式构造请求体 let requestBody: [String: Any] = [ "instances": [ ["content": input] ] ] do { request.httpBody = try JSONSerialization.data(withJSONObject: requestBody) } catch { completion(.failure(error)) return } let task = URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { completion(.failure(error)) return } guard let responseData = data else { completion(.failure(NSError(domain: "DataError", code: 0, userInfo: [NSLocalizedDescriptionKey: "未获取到返回数据"]))) return } // 根据模型输出格式解析结果 do { guard let resultDict = try JSONSerialization.jsonObject(with: responseData) as? [String: Any], let predictions = resultDict["predictions"] as? [[String: Any]], let outputContent = predictions.first?["content"] as? String else { completion(.failure(NSError(domain: "ParseError", code: 0, userInfo: [NSLocalizedDescriptionKey: "结果解析失败"]))) return } completion(.success(outputContent)) } catch { completion(.failure(error)) } } task.resume() }
方式2:Google Cloud Swift SDK调用
使用官方SDK可简化调用流程,减少手动构造请求的代码:
- 在
Podfile中添加依赖:pod 'GoogleCloudVertexAI'(需确认最新SDK版本) - 同样通过Google Sign-In完成身份验证
- Swift代码示例:
import GoogleCloudVertexAI func predictWithVertexAISDK(input: String) async throws -> String { // 替换为你的项目ID和区域 let vertexAI = VertexAI(projectID: "你的项目ID", location: "us-central1") let endpoint = try await vertexAI.endpoint(name: "你的端点ID") let predictionResponse = try await endpoint.predict(instances: [["content": input]]) return predictionResponse.predictions.first?["content"] as? String ?? "" }
三、关键注意事项
- 安全优先:禁止在iOS客户端硬编码服务账号JSON密钥,优先采用Google Sign-In授权或后端代理请求(后端用服务账号调用Vertex AI,客户端仅与自身后端交互)。
- 权限配置:确保授权账号拥有
aiplatform.endpoints.predict权限。 - 格式匹配:请求体和结果解析必须严格对应你部署模型的输入输出格式(比如图像模型可能需要传递base64编码的图像数据)。
内容的提问来源于stack exchange,提问作者Atom
相关产品推荐
相关产品推荐

