本文档介绍了如何开始使用 iOS 版 Headless Mobile SDK。
借助 Headless Mobile SDK for iOS,您可以直接将 CCAI Platform 提供的支持添加到您自己的内置 iOS 体验中,而无需使用预构建的 CCAI Platform 界面。
您无需呈现 CCAI Platform 品牌微件,而是:
将 CCAI iOS SDK 集成到您的应用中。
自行构建屏幕、导航和视觉设计。
使用 SDK 可执行以下操作:
发起和管理聊天和语音会话。
提供电子邮件、预约通话和转移选项。
支持智能操作、附件和会话后流程(CSAT、调查问卷、虚拟客服)。
CCAI Platform 处理联络中心逻辑(路由、队列、渠道、配置、报告)。您拥有整个应用体验(界面、流程和品牌)。
如果您更喜欢预构建的可配置界面,而不是自行构建界面,请使用标准移动 SDK。
要求
以下是集成 iOS 版 Headless Mobile SDK 的要求。
iOS 平台要求
iOS 最低版本:iOS 16.6 或更高版本
语言:Swift
IDE:应用支持的最新稳定版 Xcode
架构:当前 Xcode 工具链支持的标准 iOS 架构。
应用权限
由于您的内置应用会处理智能操作(拍摄照片、录制视频或验证身份)的界面,因此您必须声明 Apple 的强制性隐私权限。
将以下键添加到 Info.plist 中,并说明应用如何使用这些数据:
NSCameraUsageDescription:用户拍摄和发送照片/视频,或执行代理请求的智能操作时需要。NSMicrophoneUsageDescription:即时语音通话和录制有声视频时需要使用。NSPhotoLibraryUsageDescription:用户必须授予此权限,才能从相机胶卷中上传现有照片或视频。NSFaceIDUsageDescription:如果您支持生物识别验证智能操作,则必须提供此属性。
CCAI 平台实例要求
您需要有权访问 CCAI 平台实例的开发者设置,才能获取以下详细信息:
公司密钥
公司密码
主机网址 - CCAI 平台的主机名(例如
your_subdomain.ccaiplatform.com)
这些值用于以下用途:
公司密钥 + 主机网址:在 iOS 应用中初始化 SDK。
公司密钥代码:在后端中,用于对验证用户身份的 JSON Web 令牌 (JWT) 进行签名。
推送通知
您可以选择是否接收推送通知。如果没有这些权限,当应用处于打开状态时,用户发起的对话(包括智能体在对话期间请求的智能操作)和通话仍可正常进行。您只需要针对以下情况启用推送通知:来电(客服人员回电和预约通话)、客服人员在通话期间请求的智能操作,以及应用在后台运行或关闭时有关客服人员新消息和聊天更新的提醒。为此,您需要:
适用于标准推送通知的 Apple 推送通知服务 (APNs) 配置。
VoIP 服务证书(如果您的应用会接收来电)。
您将学习以下内容:
在 Apple 开发者门户中配置 APN,如果您的应用会接收来电,请配置 VoIP 凭据。
在 CCAI Platform 管理员门户中,依次前往设置 > 开发者设置 > 移动应用,上传转换后的证书。
在应用中注册接收远程通知,如果应用会接收来电,则注册接收 VoIP 推送。
将相应的设备令牌转发到 SDK。
在 Target > Signing & capabilities(目标 > 签名和功能)中,为您使用的功能启用相应功能:
推送通知功能。
后台模式功能,并勾选以下选项:
Voice over IP - VoIP 推送通知(来电)需要此权限。
音频、AirPlay 和画中画 - 必须启用,才能在应用处于后台时继续播放语音通话音频。
远程通知 - 标准 APN 推送传送需要此权限。
无头 iOS SDK 如何融入您的应用
Headless Mobile SDK for iOS 可分为三层:
CCAI Platform 平台和 SDK
该 SDK 可安全地与 CCAI Platform 平台交互,并提供:
使用 JSON Web 令牌 (JWT) 进行身份验证。
队列和渠道路由元数据(聊天、语音、预约通话、电子邮件、外部转移链接)。
实时会话状态管理。
用于智能操作、文件附件和屏幕共享的安全传输流水线。
偏转逻辑和会话后层次结构评估。
您的 iOS 应用(界面和逻辑由您处理)
您可以控制整个视觉和导航体验:
入口点:例如,帮助标签页或与我们联系按钮。
菜单:您如何显示队列(例如结算、技术支持)。
会话中界面:自定义聊天气泡、通话界面和控件。
应用的功能:调用 SDK API 以启动和结束会话、监听 SDK 事件,以及驱动视图控制器导航。
CCAI 平台管理员门户配置
CCAI 平台管理员负责配置互动规则(营业时间、可用渠道、等待时间阈值和调查问卷)。SDK 会读取此配置,并将其作为原始数据和事件公开给您的应用。您可以决定如何在屏幕上绘制该配置。
检索公司凭证
在集成 SDK 之前,请从 CCAI Platform 实例获取凭据:
使用管理员账号登录 CCAI Platform 管理员门户。
依次前往设置 > 开发者设置。
在公司密钥和密码下,复制以下内容:
公司密钥
公司密码
记下您的主机网址:CCAI 平台的主机名(例如
your_subdomain.ccaiplatform.com)。
您将使用:
在 iOS 应用中:公司密钥 + 主机网址。
在后端服务器中:用于为以下对象签署 JWT 的公司密钥代码:
最终用户身份验证。
CCAI Platform 使用的可选自定义数据或上下文。
将 SDK 添加到您的 iOS 应用
Headless SDK v3 采用模块化架构构建。CCAIKit 软件包产品包含每个模块:聊天 (CCAIChat)、语音和预约通话 (CCAICall) 以及屏幕共享 (CCAIScreenShare)。如果您的应用只需要其中一项功能,请添加该功能的产品(CCAIChat、CCAICall 或 CCAIScreenShare),而不是 CCAIKit;每个产品都包含核心 SDK。
如需在应用中集成 iOS SDK,请按以下步骤操作。
方案 A:Swift Package Manager(推荐)
请将以下内容添加到
Package.swift文件:dependencies: [ .package(url: "https://github.com/UJET/ccai-ios-sdk.git", from: "3.5.0") ], targets: [ .target( name: "YourTargetName", dependencies: [ .product(name: "CCAIKit", package: "ccai-ios-sdk") ] ) ]在
AppDelegate文件中导入CCAIKit:import CCAIKit如果您的项目是 SwiftUI,请在
App结构体中声明@UIApplicationDelegateAdaptor:@main struct YourAppName: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate // ... }
在 Xcode 中,您可以改为选择 File(文件)> Add Package Dependencies…(添加软件包依赖项…),输入 https://github.com/UJET/ccai-ios-sdk,然后将 CCAIKit 产品添加到应用目标。
导入 SDK 模块并不会使 Foundation 可用。在每个文件中,导入该文件使用的类型或 API 所属的框架和 SDK 模块:例如,import Foundation 对应 DispatchQueue、UUID 或 Date,import
CCAIKit 对应 CCAI。
初始化无头 SDK
在应用启动期间初始化 SDK。由于 SDK 的模块化架构,您必须先初始化核心 CCAI 系统,然后注册特定的服务模块(例如聊天或屏幕共享)。
基本初始化
SDK 使用一个 InitOptions 结构体,该结构体捆绑了所有必需的配置:
import UIKit
import CCAIKit
import CCAIChat // If using Chat
import CCAICall // If using voice or scheduled calls
import CCAIScreenShare // If using Screen Share
class AppDelegate: NSObject, UIApplicationDelegate, CCAIDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// 1. Configure initialization options
let options = InitOptions(
key: "YOUR_COMPANY_KEY",
urlHost: "your_subdomain.ccaiplatform.com",
delegate: self,
cacheAuthToken: true // Whether to cache the auth token (defaults to true)
)
// 2. Initialize the Core SDK
do {
try CCAI.shared.initialize(options: options)
} catch {
print("Failed to initialize CCAI: \(error.localizedDescription)")
return true
}
// Optional: set the SDK language (ISO 639 code; defaults to "en")
CCAI.shared.languageService?.languageCode = "en"
// 3. Initialize Feature Modules
// Chat - minimal (no options required)
CCAI.shared.initializeChat()
// Chat - with optional configuration
// let chatOptions = ChatOptions(
// webFormHandler: { request in await presentWebForm(request) }, // Optional: render web forms in your own UI
// downloadTranscriptVisibility: .hideInPostChat // Hide the post-chat download affordance
// )
// To set a chat greeting, pass greeting: in the ChatRequest
// CCAI.shared.initializeChat(chatOptions)
// Voice (required whenever your app uses voice or scheduled calls)
CCAI.shared.initializeCall()
// Screen Share (optional)
// let screenShareOptions = ScreenShareOptions(
// key: "YOUR_SCREEN_SHARE_LICENSE_KEY", // License Key (Settings > Developer Settings > Screen Share)
// domain: "https://your-screen-share-domain.example.com" // Optional: the Screen Share Domain URL
// )
// CCAI.shared.initializeScreenShare(screenShareOptions)
return true
}
// ... CCAIDelegate methods (Authentication) go here ...
}
InitOptions 配置参考文档
public struct InitOptions {
/// The company key used for authentication
public let key: String
/// The host URL for CCAI platform (for example, "my-unique-tenant.uc1.ccaiplatform.com")
public let urlHost: String
/// The delegate that handles authentication
public var delegate: CCAIDelegate?
/// Whether to cache the authentication token (defaults to true)
public let cacheAuthToken: Bool
}
可用的 SDK 服务
初始化后,您可以通过 CCAI.shared 单例访问各种服务:
let authService = CCAI.shared.authService
let companyService = CCAI.shared.companyService
let queueMenuService = CCAI.shared.queueMenuService
let languageService = CCAI.shared.languageService
let pushNotificationService = CCAI.shared.pushNotificationService
let endUserService = CCAI.shared.endUserService
let chatService = CCAI.shared.chatService // Only available after initializeChat()
let screenShareService = CCAI.shared.screenShareService // Only available after initializeScreenShare()
let callService = CCAI.shared.callService // Only available after initializeCall()
let rateService = CCAI.shared.rateService // For CSAT ratings and survey submission
let smartActionService = CCAI.shared.smartActionService // Dedicated service for smart action lifecycle
提取公司配置
初始化后,使用 companyService 提取公司级配置。这有助于在用户进入队列之前填充语言选择器、显示公司名称或读取支持联系信息。
do {
let company = try await CCAI.shared.companyService?.get()
print("Company: \(company?.displayName ?? "Unknown")")
} catch {
print("Failed to get company info: \(error)")
}
对最终用户进行身份验证
Headless Mobile SDK 使用 JSON Web 令牌 (JWT) 对用户进行身份验证,并安全地将上下文信息传递给代理的 CRM。
工作原理
该 SDK 使用简化的两步异步身份验证流程:
SDK 确定需要对用户进行身份验证。
它会调用您的
CCAIDelegate方法ccaiShouldAuthenticate(),这是一个异步函数。您的应用使用公司密钥代码在后端服务器上远程对 JWT 进行签名。
然后,您的应用会将已签名的 JWT 传递给
CCAI.shared.authService?.authenticate(jwt),以换取身份验证令牌。身份验证令牌会返回到 SDK 以完成关联。
实现 CCAIDelegate 以进行身份验证
您的应用必须实现 CCAIDelegate 协议。SDK 在需要身份验证时会调用单个异步委托方法。
CCAIDelegate 协议
public protocol CCAIDelegate: AnyObject {
/// Authenticates the end user and returns an auth token
func ccaiShouldAuthenticate() async -> String?
}
实现示例 (Swift)
class AppDelegate: CCAIDelegate {
func ccaiShouldAuthenticate() async -> String? {
// 1. Sign JWT remotely on your backend server
guard let jwt = await signJWTRemotely() else { return nil }
// 2. Authenticate JWT using authService to get an auth token
return try? await CCAI.shared.authService?.authenticate(jwt)
}
}
将自定义数据传递给 CRM
如果您想将情境数据(例如,用户当前的设备操作系统、其位置或其账号层级)传递给代理,则您的后端必须在对 JWT 载荷进行签名之前,将 custom_data 对象注入到 JWT 载荷中。
每条自定义数据都必须采用 JSON 对象格式,其中包含 label(代理看到的内容)、value 和 type。
支持的数据类型
string:标准文本(例如“iPhone 14 Pro”)。number:整数或浮点数(例如 1234 或 99.99)。date:13 位 UTC Unix 时间戳,包括毫秒(例如 1537399655992)。url:标准 HTTP/HTTPS 网址格式。boolean:标准 true 或 false 值。
预留的 CRM 键
CCAI Platform 支持特定的预留键,这些键可触发平台中的内置行为,例如将用户标记为 VIP 或向客服人员发出有关不良行为者的警告。这些值必须采用布尔值类型,并且仅在载荷使用安全 JWT 方法签名时才会被接受。
reserved_verified_customer:指明客户是否已通过内部系统的成功身份验证。reserved_bad_actor:向代理标记该用户可能是垃圾内容发布者或欺诈性账号。reserved_repeat_customer:指明此客户最近是否频繁联系支持团队。
包含预留键的载荷示例
{
"iat": 1537399656,
"exp": 1537400256,
"custom_data": {
"reserved_verified_customer": {
"label": "Verified Customer",
"value": true,
"type": "boolean"
},
"reserved_bad_actor": {
"label": "Bad Actor",
"value": false,
"type": "boolean"
},
"reserved_repeat_customer": {
"label": "Repeat Customer",
"value": false,
"type": "boolean"
}
}
}
管理身份验证令牌
该 SDK 还提供了手动更新或清除缓存的身份验证令牌的方法:
// Set a new auth token
CCAI.shared.authService?.updateAuthToken("new_auth_token")
// Clear the current token (for example, on user logout)
CCAI.shared.authService?.updateAuthToken(nil)
自定义数据 JWT 载荷架构
当您的后端构建要使用公司密钥签名的最终载荷时,必须严格遵循此架构。请注意强制性 iat(签发时间)和 exp(到期时间)时间戳。
{
"iat": 1537399656,
"exp": 1537400256,
"custom_data": {
"os_version": {
"label": "OS Version",
"value": "16.4",
"type": "string"
},
"membership_tier": {
"label": "Membership Tier",
"value": "Platinum",
"type": "string"
},
"ssn_last_four": {
"label": "SSN",
"value": "1234",
"type": "string",
"invisible_to_agent": true
},
"reserved_verified_customer": {
"label": "Verified Customer",
"value": true,
"type": "boolean"
}
}
}
启用推送通知
SDK 会将推送通知用于以下用途:
来电(客服人员回电和预约通话)。
客服人员在通话期间请求的智能操作。
当应用在后台运行或关闭时,提醒您有新的客服人员消息和聊天更新。
配置证书
CCAI Platform 使用两种类型的 Apple 推送证书,这些证书保存在 CCAI Platform 管理员门户中:
用于标准远程推送通知的 Apple 推送通知服务 (APNs) SSL 证书。
用于来电的 VoIP 服务证书。仅当应用接收来电时,才需要此权限。
这两个证书都是在 Apple Developer 门户中创建,转换为 PEM 格式,然后上传到 CCAI Platform 管理员门户。
创建 APNs SSL 证书
请按照以下步骤(基于 Apple 的官方建立与 APNs 的基于证书的连接指南)创建 APNs SSL 证书。
登录 developer.apple.com,然后前往 Certificates, Identifiers & Profiles(证书、标识符和个人资料)。
选择 + 按钮以创建新证书。
在“Services”(服务)下,选择 Apple Push Notification service SSL (Sandbox & 生产环境)(Apple 推送通知服务 SSL [沙盒和生产])。
选择与应用的软件包标识符匹配的应用 ID,然后选择继续。
上传在 Mac 上通过“钥匙串访问”生成的证书签名请求 (CSR):
依次打开钥匙串访问 > 证书助理 > 向证书颁发机构请求证书…
输入您的电子邮件地址,将“CA 电子邮件地址”留空,选择保存到磁盘,然后选择继续。
依次选择继续和下载,下载生成的
.cer文件。双击
.cer文件,将其安装到钥匙串中。在“钥匙串访问”中,找到已安装的证书,右键点击该证书,然后选择导出…,将其保存为
.p12文件。系统会提示您设置导出密码。使用
openssl将.p12文件转换为 PEM 格式:# Extract the certificate openssl pkcs12 -in apns_certificate.p12 -out apns_cert.pem -clcerts -nokeys # Extract the private key openssl pkcs12 -in apns_certificate.p12 -out apns_key.pem -nocerts -nodes # (Optional) Combine into a single PEM file cat apns_cert.pem apns_key.pem > apns_combined.pem
创建 VoIP 服务证书
VoIP 服务证书允许您的应用通过 Apple 的 PushKit 框架接收高优先级推送通知,该框架可以将您的应用从终止状态唤醒以处理来电。如需了解最新的官方步骤,请参阅 Apple 开发者文档中的创建 VoIP 服务证书。
登录 developer.apple.com,然后前往 Certificates, Identifiers & Profiles(证书、标识符和个人资料)。
选择 + 按钮以创建新证书。
在“Services”(服务)下,选择 VoIP Services Certificate(VoIP 服务证书)。
选择与应用的软件包标识符匹配的应用 ID,然后选择继续。
上传您为 APNs SSL 证书生成的同一证书签名请求 (CSR)(或创建新证书)。
依次选择继续和下载,下载生成的
.cer文件。双击
.cer文件,将其安装到钥匙串中。在“钥匙串访问”中,找到已安装的 VoIP 服务证书,右键点击该证书,然后选择导出…,将其保存为
.p12文件。使用
openssl将.p12文件转换为 PEM 格式:# Extract the certificate openssl pkcs12 -in voip_certificate.p12 -out voip_cert.pem -clcerts -nokeys # Extract the private key openssl pkcs12 -in voip_certificate.p12 -out voip_key.pem -nocerts -nodes # (Optional) Combine into a single PEM file cat voip_cert.pem voip_key.pem > voip_combined.pem
将证书上传到 CCAI Platform 管理员门户
登录 CCAI Platform 管理员门户。
依次前往设置 > 开发者设置 > 移动应用。
上传 APNs PEM 证书。
如果您的应用会接收来电,请上传 VoIP PEM 证书。
请求推送通知权限
该 SDK 提供了一种便捷方法,可请求通知权限,并在用户授予权限后向 APNs 注册您的应用。如果您的应用在首次聊天、即时通话或语音信息开始时仍未请求通知权限,SDK 会在此时请求。如需控制提示出现的时间,请提前自行请求权限,例如在新手入门期间。
该方法不会返回用户的选择。如需跟踪该权限,请在请求权限之前订阅 grantStatusChanged。发布者不会重放先前的值:一旦 APNs 设备令牌到达 SDK,它就会发布 true;如果用户拒绝权限或注册失败,它就会发布 false,因此在请求之后进行的订阅可能会错过答案。
// 1. Subscribe first: grantStatusChanged doesn't replay earlier values
CCAI.shared.pushNotificationService?.grantStatusChanged
.receive(on: DispatchQueue.main)
.sink { granted in
print(granted ? "Push notifications enabled" : "Push notifications disabled")
}
.store(in: &cancellables)
// 2. Then request permission and register with APNs
let options: UNAuthorizationOptions = [.alert, .sound]
try await CCAI.shared.pushNotificationService?.registerForPushNotifications(options: options)
注册接收远程通知
在 AppDelegate 中实现推送通知委托。SDK 提供了 pushNotificationService,用于转发令牌:
import CCAIKit
class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
CCAI.shared.pushNotificationService?.updatePushToken(
data: deviceToken,
type: .apns
)
}
func application(
_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error
) {
CCAI.shared.pushNotificationService?.updatePushToken(
data: nil,
type: .apns
)
}
}
此外,请务必在 Xcode 的 Target > Signing & capabilities(目标 > 签名和功能)标签页中,为远程通知启用 Capabilities > Push notifications(功能 > 推送通知)和 Background modes(后台模式)。
处理传入的推送通知
收到推送载荷后,请将其转发给 SDK 进行处理:
func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
Task {
// handlePushNotification is async, so call it from a Task
await CCAI.shared.pushNotificationService?.handlePushNotification(userInfo)
completionHandler(.newData)
}
}
SDK 会处理 CCAI Platform 发送的载荷,并在 pushNotificationService 发布商(例如 chatNotificationReceived、callNotificationReceived 或 requestNotificationReceived)上发布每个载荷。
注册接收 VoIP 推送通知
对于来电,SDK 需要 VoIP 推送令牌。VoIP 推送会以高优先级传送,并且可以将应用从终止状态唤醒。如果您的应用不接收来电,请跳过此部分。
第 1 步:导入 PushKit、UIKit、CCAIKit 和 CCAICall,在 AppDelegate 的属性中保留 PKPushRegistry,并在 didFinishLaunchingWithOptions 中对其进行配置:
import PushKit
import UIKit
import CCAIKit
import CCAICall
class AppDelegate: NSObject, UIApplicationDelegate, PKPushRegistryDelegate {
// Keep a strong reference: a registry held only in a local constant is
// released, and stops delivering VoIP tokens and pushes
private let voipRegistry = PKPushRegistry(queue: .main)
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// ... SDK initialization ...
// Register for VoIP push notifications
voipRegistry.delegate = self
voipRegistry.desiredPushTypes = [.voIP]
return true
}
}
第 2 步:实现 PKPushRegistryDelegate 方法,将 VoIP 令牌和载荷转发到 SDK:
// MARK: - PKPushRegistryDelegate
func pushRegistry(
_ registry: PKPushRegistry,
didUpdate credentials: PKPushCredentials,
for type: PKPushType
) {
guard type == .voIP else { return }
// Forward the VoIP token to the SDK
CCAI.shared.pushNotificationService?.updatePushToken(
data: credentials.token,
type: .voip
)
}
func pushRegistry(
_ registry: PKPushRegistry,
didInvalidatePushTokenFor type: PKPushType
) {
// Clear the VoIP token
CCAI.shared.pushNotificationService?.updatePushToken(
data: nil,
type: .voip
)
}
func pushRegistry(
_ registry: PKPushRegistry,
didReceiveIncomingPushWith payload: PKPushPayload,
for type: PKPushType,
completion: @escaping () -> Void
) {
guard type == .voIP else {
completion()
return
}
// Forward the VoIP payload to the SDK using the `handleVoIPPush`
// extension on `CCAI` (defined in the `CCAICall` module). The SDK
// takes ownership of the call lifecycle; invoke PushKit's completion
// handler in the trailing closure once the SDK has accepted the
// payload.
CCAI.shared.handleVoIPPush(payload: payload.dictionaryPayload) { completion() }
}
handleVoIPPush 也会在冷启动时(在 CCAI.shared.initializeCall() 运行之前)运行:SDK 会立即向 CallKit 报告来电,并在您初始化通话模块后将其交给通话服务。