Swift 快速上手(IMKit)
本页面向 Swift 工程:从零完成 IMKit 接入(IMLib 初始化 → 连接 → 挂载会话列表 → 收发文本)。Objective-C 工程见 Objective-C 接入。
- 环境
Xcode 15+、iOS 13+、Swift 5.9;CocoaPods 1.10+ 或 SPM。
- 导入
`pod 'ImpIaaSIMKit', '~> 1.0'`,或 Xcode 添加 Swift Package。
- 初始化 IMLib
`ImpIaaSIM.client(options:)`;幂等,不建立连接。
- 建立连接
`await client.connect(token:)`;成功后触发 CONNECTED。
- 挂载 IMKit
`IMKitFacade(options:)` + `mount(in: view)`;宿主负责导航。
- 收发验证
发送文本、监听 MESSAGES、拉会话列表;用两个账号验证。
1. 导入
Text
# Podfile
platform :ios, '13.0'
target 'YourApp' do
pod 'ImpIaaSIMKit', '~> 1.0' # 自动依赖 ImpIaaSIM
end2. 初始化与连接
Swift
import ImpIaaSIM
final class IMService {
static let shared = IMService()
private(set) var client: IMPClient!
func setup() {
client = ImpIaaSIM.client(options: IMPClientOptions(
appkey: "YOUR_APP_KEY",
serverUrl: "https://im.example.com"
))
}
func connect(token: String) async {
let res = await client.connect(token: token)
if res.code != 0 { print("connect failed:", res.code, res.msg ?? "") }
}
}3. 挂载 IMKit
Swift
import ImpIaaSIMKit
let controller = IMPChatViewController(conversationType: .privateChat, targetId: "user2")
controller.client = client
navigationController.pushViewController(controller, animated: true)4. 收发与事件
Swift
final class MessageListener: IMPEventListener {
func onEvent(_ payload: IMPEventPayload) {
if case .messages(let messages) = payload {
// 门面已处理会话与气泡;自定义页面时可在此更新列表
print("received", messages.count)
}
}
}
let listener = MessageListener()
client.addEventListener(.messages, listener: listener)
let sent = await client.sendTextMessage(
conversationType: .privateChat, targetId: "user2", text: "你好,NI PaaS", options: nil
)
if sent.code != 0 { print("send failed:", sent.code, sent.msg ?? "") }两个账号验证
同一进程只允许一个登录态;验证收发请开两个模拟器或一台真机 + 一个模拟器。
下一步
- IMLib 快速开始(含 Objective-C 示例)
- IMKit 功能列表:10 个组件能力矩阵
- 组件 API:props / events 明细
- 主题定制、多语言