iOS SDK
iOS SDK 基于 URLSessionWebSocketTask 实现,支持 Swift 与 Objective-C,采用 Combine / async-await 暴露事件流。
准备中
完整接入文档与 CocoaPods / SPM 集成说明正在整理。当前可基于 WebSocket V2 协议 自行实现,或联系商务获取早期访问。
计划支持
- Swift 5.7+ / Objective-C
- iOS 13+
- CocoaPods / Swift Package Manager
- Combine / async-await 双 API
- AVFoundation 录音 / 播放整合
- VoIP 后台运行支持
- ARKit 摄像头帧上传(多模态场景)
Swift 参考实现示例
在正式 SDK 发布前,可参考以下实现快速接入:
示例中的 appId、appKey 从开发管理获取,deviceSn 使用设备实例中对应设备的序列号。生产环境不要把 AppKey 打包进 App,应使用服务端代签。
1. WebSocket 客户端封装
import Foundation
class AiotWebSocketClient {
private var webSocketTask: URLSessionWebSocketTask?
private let endpoint: String
private let appId: String
private let appKey: String
private let deviceSn: String
var onTextOutput: ((String, String) -> Void)?
var onAudioFrame: ((Data) -> Void)?
var onDispatchInstruct: ((InstructEvent) -> Void)?
var onError: ((Int, String) -> Void)?
init(endpoint: String, appId: String, appKey: String, deviceSn: String) {
self.endpoint = endpoint
self.appId = appId
self.appKey = appKey
self.deviceSn = deviceSn
}
func connect() {
let timestamp = Int64(Date().timeIntervalSince1970 * 1000)
let uniqueId = UUID().uuidString
let signature = generateSignature(appId: appId, timestamp: timestamp, uniqueId: uniqueId, appKey: appKey)
var urlComponents = URLComponents(string: endpoint)!
urlComponents.queryItems = [
URLQueryItem(name: "sn", value: deviceSn),
URLQueryItem(name: "app_id", value: appId),
URLQueryItem(name: "timestamp", value: "\(timestamp)"),
URLQueryItem(name: "unique_id", value: uniqueId),
URLQueryItem(name: "signature", value: signature.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))
]
webSocketTask = URLSession.shared.webSocketTask(with: urlComponents.url!)
webSocketTask?.resume()
receiveMessage()
}
func startTask(inputMode: String, outputMode: String) {
let payload: [String: Any] = [
"header": ["action": "start_task"],
"payload": [
"input_mode": inputMode,
"output_mode": outputMode,
"input_audio_codec": "pcm",
"input_sample_rate": 16000
]
]
sendJSON(payload)
}
func sendAudio(_ data: Data) {
webSocketTask?.send(.data(data)) { _ in }
}
func sendText(_ text: String) {
let payload: [String: Any] = [
"header": ["action": "start_task"],
"payload": [
"input_mode": "text",
"output_mode": "text",
"user_input": text
]
]
sendJSON(payload)
}
func endTask() {
let payload: [String: Any] = [
"header": ["action": "end_task"],
"payload": [:]
]
sendJSON(payload)
}
private func receiveMessage() {
webSocketTask?.receive { [weak self] result in
switch result {
case .success(let message):
self?.handleMessage(message)
self?.receiveMessage() // 继续接收
case .failure(let error):
self?.onError?(-1, error.localizedDescription)
}
}
}
private func handleMessage(_ message: URLSessionWebSocketTask.Message) {
switch message {
case .string(let text):
handleTextMessage(text)
case .data(let data):
onAudioFrame?(data)
@unknown default:
break
}
}
private func handleTextMessage(_ text: String) {
guard let data = text.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let header = json["header"] as? [String: Any],
let action = header["action"] as? String else {
return
}
if action == "text_output", let payload = json["payload"] as? [String: Any] {
let type = payload["type"] as? String ?? ""
let result = payload["result"] as? String ?? ""
onTextOutput?(type, result)
} else if action == "dispatch_instruct" {
// 处理指令下发
}
}
private func sendJSON(_ payload: [String: Any]) {
if let data = try? JSONSerialization.data(withJSONObject: payload),
let string = String(data: data, encoding: .utf8) {
webSocketTask?.send(.string(string)) { _ in }
}
}
private func generateSignature(appId: String, timestamp: Int64, uniqueId: String, appKey: String) -> String {
let signObj = ["app_id": appId, "timestamp": "\(timestamp)", "unique_id": uniqueId]
let sorted = signObj.sorted { $0.key < $1.key }
let jsonString = sorted.map { "\"\($0.key)\":\"\($0.value)\"" }.joined(separator: ",")
let fullJson = "{\(jsonString)}"
// HMAC-SHA256 + Base64
// 需要引入 CommonCrypto 或 CryptoKit
return hmacSHA256(message: fullJson, key: appKey)
}
}
2. 使用示例
let client = AiotWebSocketClient(
endpoint: "wss://aikit.xfyun.cn/gw/ws/open/api/v2/agentChat",
appId: "YOUR_TENANT_APP_ID",
appKey: "YOUR_APP_KEY",
deviceSn: "DEVICE-SN-001"
)
client.onTextOutput = { type, result in
if type == "agent_response_text" {
print("AI回复: \(result)")
}
}
client.onAudioFrame = { data in
// 播放TTS音频
}
client.connect()
client.startTask(inputMode: "text", outputMode: "text")
client.sendText("今天天气怎么样?")
临时接入方案
当前可参考 Android SDK 与 V2 协议文档,用 URLSessionWebSocketTask 实现一份原生客户端:
let url = URL(string: "wss://aikit.xfyun.cn/gw/ws/open/api/v2/agentChat?...")!
let task = URLSession.shared.webSocketTask(with: url)
task.resume()
task.send(.string(#"{"header":{"action":"start_task"},"payload":{...}}"#)) { _ in }
task.receive { result in
// handle text / binary frames
}
完整 iOS SDK 上线时间请关注 发布公告。