移动端 SDK
iOS SDK
通过 CocoaPods 或本地 Swift package 安装 STINGIM iOS SDK 并接入应用内客服:初始化、身份、界面、事件与令牌存储。
iOS SDK(版本 1.1.0)包含两个产品:StingimChannel(核心库:连接、消息、身份,仅依赖 Foundation,无第三方依赖)和 StingimChannelUI(适用于 UIKit 和 SwiftUI 的现成聊天界面)。
环境要求
| 项目 | 要求 |
|---|---|
| 部署目标 | iOS 13.0+ |
| 工具链 | Xcode 16+、Swift 6.0(swift-tools-version:6.0) |
| 依赖 | 无(使用系统 URLSession 和 URLSessionWebSocketTask) |
| 隐私清单 | 已包含(PrivacyInfo.xcprivacy;无跟踪) |
安装
iOS SDK 以源码包形式发布在本站,无需账号、令牌或 Git 访问权限。可以使用 CocoaPods,或把源码包作为本地 Swift package 添加到 Xcode。
CocoaPods
platform :ios, '13.0'
target 'YourApp' do
pod 'StingimChannel/UI', :podspec => 'https://stingim.com/sdk/ios/StingimChannel.podspec' # 内置界面(包含核心库)
# pod 'StingimChannel', :podspec => 'https://stingim.com/sdk/ios/StingimChannel.podspec' # 仅核心库
end然后运行 pod install。StingimChannel.podspec 始终指向最新版本;要锁定当前版本,请改用 https://stingim.com/sdk/ios/StingimChannel-1.1.0.podspec。podspec 会下载 StingimChannel-1.1.0.zip 并校验其 SHA-256。
使用 CocoaPods 时,核心库与界面会编译进同一个模块 StingimChannel。需要同时兼容 CocoaPods 与 Swift Package Manager 的代码可按条件导入界面模块:
import StingimChannel
#if canImport(StingimChannelUI)
import StingimChannelUI
#endifSwift Package Manager(本地包)
- 下载 StingimChannel-1.1.0.zip,用
shasum -a 256 StingimChannel-1.1.0.zip与下载页上的值核对。 - 解压到工程目录内,例如
Vendor/StingimChannel-1.1.0(目录中包含Package.swift),并随应用一起提交,确保 CI 构建也能找到。 - 在 Xcode 中选择 File → Add Package Dependencies… → Add Local…,选中该目录,然后把 StingimChannelUI(内置界面)或仅 StingimChannel(自定义界面)添加到应用 target。
在 Package.swift 中:
dependencies: [
.package(path: "Vendor/StingimChannel-1.1.0")
],
targets: [
.target(name: "YourApp", dependencies: [
.product(name: "StingimChannelUI", package: "StingimChannel-1.1.0") // 内置界面(包含核心库)
// .product(name: "StingimChannel", package: "StingimChannel-1.1.0") // 仅核心库
])
]升级时用新版本目录替换并更新路径即可。
为什么没有包 URL?
Swift Package Manager 只能从 Git 仓库解析远程源码包,或使用预编译 XCFramework 形式的二进制包(binaryTarget(url:checksum:))。SDK 没有托管在公开的 Git 平台上,目前也未发布预编译 XCFramework,因此 SPM 用户需将源码包作为本地包添加。CocoaPods 无需额外步骤。
初始化
生产环境:从服务端获取 token
你的服务端用 App Secret 换取访客 token(方法),并返回 contactId、contactToken 和 channelId:
import StingimChannel
Task {
do {
try await Stingim.shared.start(
contactId: bootstrap.contactId,
contactToken: bootstrap.contactToken,
channelId: bootstrap.channelId,
projectId: bootstrap.projectId, // 可选:用于 AI 身份提示 / 营业时间
pluginId: bootstrap.pluginId) // 可选:同上
} catch {
print("Support chat failed to start: \(error)")
}
}start 会自动连接 WebSocket(除非关闭了 autoConnect)。重复调用 start 是安全的,会刷新身份。如需在不打扰用户的情况下刷新过期 token,请设置处理函数:
Stingim.shared.reauthenticationHandler = {
let b = try await MyBackend.fetchStingimToken()
return (contactId: b.contactId, contactToken: b.contactToken)
}开发环境:由 SDK 换取 App Secret
仅适用于开发或受控环境。切勿将 App Secret 放进应用二进制、Info.plist 或远程配置中。
import StingimChannel
Task {
do {
try await Stingim.shared.start(
pluginId: "<plugin_id>",
appSecret: "<app_secret>",
channelId: "<channel_id>")
} catch {
print("Support chat failed to start: \(error)")
}
}配置
请在 start 之前调用 configure:
var cfg = StingimConfig()
cfg.apiBaseUrl = "https://api.stingim.com" // 默认值
cfg.socketBaseUrl = "wss://msg.stingim.com" // 默认值(不含 /visitor)
cfg.autoConnect = true // start 后自动连接
cfg.cacheMessages = true // 本地离线缓存
cfg.debugMode = false // 通过 print("[Stingim] …") 输出日志,绝不包含 token 或消息内容
Stingim.shared.configure(cfg)其他字段:heartbeatIntervalSec(25)、inactivityTimeoutSec(60)、backoff(无限重试,间隔上限 30 秒)、deviceId、reconnectOnForeground(true)、reconnectOnNetworkChange(true)。
用户身份
在服务端按与网页挂件完全相同的方式为已登录用户签名:user_hash = hex(HMAC-SHA256(secret, user_id));如需设置过期时间,则对 "\(user_id):\(exp)" 签名。生产环境中,由服务端将签名字段发送给 open-create-contact。直连模式下,将其传给 SDK:
let identity = StingimUserIdentity(userId: user.id, userHash: signed.hash, userHashExp: signed.exp,
userName: user.name, userEmail: user.email)
try await Stingim.shared.start(pluginId: pid, appSecret: secret, channelId: cid, identity: identity)
print(Stingim.shared.identityStatus) // .verified / .unverified / .rejected / .anonymoususerId 长度须为 1–255 个字符且不含控制字符,userHash 须为 64 位十六进制字符。用户退出登录时调用 await Stingim.shared.disconnect()。
内置聊天界面
UIKit:
import StingimChannelUI
let chat = StingimChatViewController(title: "在线客服")
present(UINavigationController(rootViewController: chat), animated: true)SwiftUI:
import StingimChannelUI
struct ContentView: View {
@State private var showChat = false
var body: some View {
Button("联系客服") { showChat = true }
.sheet(isPresented: $showChat) {
StingimChatView(title: "在线客服") // 自带导航栏
}
}
}在展示内置界面之前设置主题:
var theme = StingimTheme()
theme.primary = .systemIndigo
StingimTheme.current = themeStingimTheme 字段:primary、background、selfBubble、selfText、otherBubble、otherText、notificationText、timeText、inputBackground。
请在 Info.plist 中添加以下键,否则用户选择照片、打开相机或录音时应用会崩溃:NSPhotoLibraryUsageDescription、NSCameraUsageDescription、NSMicrophoneUsageDescription。
自定义界面
import StingimChannel
final class ChatViewModel: StingimDelegate {
private var conversationId = ""
init() {
Stingim.shared.delegate = self // 弱引用:请确保 view model 不被释放
Task {
try? await Stingim.shared.start(contactId: contactId, contactToken: contactToken, channelId: channelId)
conversationId = await Stingim.shared.resolveActiveConversationId() ?? ""
let page = try? await Stingim.shared.fetchMessages(pageSize: 50)
// 渲染 page?.messages
}
}
func send(_ text: String) {
Task { await Stingim.shared.send(conversationId: conversationId, text: text) }
}
func stingimDidReceiveMessage(_ m: StingimMessage) { /* 追加到列表 */ }
func stingimDidUpdateQueue(_ i: StingimQueueInfo) { /* i.queuePosition */ }
}常用操作:
let s = Stingim.shared
await s.send(conversationId: cid, text: "Hello")
try await s.sendImage(conversationId: cid, imageData: jpegData)
try await s.sendFile(conversationId: cid, fileData: data, fileName: "report.pdf")
let page = try await s.fetchMessages(pageSize: 20)
await s.markRead(conversationId: cid)
await s.setTyping(conversationId: cid, isTyping: true)
let unread = try await s.fetchUnreadCount()
let queue = try await s.fetchQueueInfo(conversationId: cid)
try await s.submitEvaluation(conversationId: cid, score: 5, remark: "Great")
let cached = s.cache?.load(conversationId: cid) // 离线缓存,用于首屏快速渲染- 发送第一条消息时,
conversationId传"";服务端创建会话后,SDK 会自动采用真实 ID。 - 文件直接上传到存储,单个文件最大 20 MB。收到的媒体请通过
previewURL(for:)展示(签名 URL,缓存 10 分钟)。 - 没有待处理的评价邀请时,
submitEvaluation会抛出错误。
Delegate 事件
所有 StingimDelegate 方法均为可选,并在主线程回调;async 方法可在任意线程调用。
| 方法 | 触发时机 |
|---|---|
stingimDidConnect() / stingimDidDisconnect(reason:) / stingimDidError(_:) | 连接状态变化 |
stingimOnlineReady() | 会话已就绪 |
stingimDidReceiveMessage(_:) | 收到新消息 |
stingimDidFailToSend(localId:error:) | 发送失败(例如被限流) |
stingimRequiresResync(conversationId:fromSeq:reason:) | 检测到消息缺口,需重新拉取历史 |
stingimDidUpdateQueue(_:) | 排队位置变化 |
stingimDidChangeConversationStatus(conversationId:status:) | 会话状态变化 |
stingimDidChangeTyping(conversationId:userId:userName:userType:isTyping:) | 客服正在输入 |
stingimDidReceiveReceipt(messageId:localId:status:timestamp:) | 送达 / 已读回执 |
stingimDidReceiveEvaluationInvite(_:) | 邀请客户评价 |
stingimDidUpdateUnreadCount(conversationId:unreadCount:) | 未读数变化 |
stingimDidReceiveRobotReplyDelta(conversationId:messageId:delta:chunkIndex:) | AI 流式回复 |
stingimDidReceiveEvent(kind:conversationId:payload:) | 其他网关事件 |
stingimDidFailAuthentication(_:) | token 被拒绝(StingimError.unauthorized) |
stingimDidChangeContact(contactId:identityStatus:) | 身份变化,需重新加载会话和历史 |
StingimError 的 case:notConnected、tokenUnavailable、encoding、decoding、http(Int, String?)、server、network、unauthorized(String)、unsupported(String);isTokenInvalid 为 true 时表示需要获取新 token。
token 存储
访客 token 以 kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly 存储在 Keychain 中;客户 ID 等非敏感值存储在 UserDefaults 中。disconnect() 会删除以上全部数据,包括本地消息缓存。直连模式下,服务端拒绝的 token(HTTP 401 或业务码 502)会被清除,SDK 会重新开始一个匿名会话;token 模式下则会调用你的 reauthenticationHandler。session_evicted(同一访客在其他地方建立了连接)不会自动重试。
1.0 暂不支持
getConversationDetail(后端仅对客服开放)。
参见故障排查。
发现错误?请发邮件至 [email protected]
