添加事件监听

  • Swift

更新时间

了解实时消息 RTM 中添加事件监听相关内容的适用场景、配置步骤、实现要点和注意事项。

如需收到消息和事件通知,你需要先实现事件监听程序,然后订阅或者加入你想要接收消息或事件通知的频道。

添加事件监听

RTM 采用统一入口的方式处理消息和事件通知,每一种消息和事件通知都有对应的事件处理程序入口,你可以在其中实现自己的业务处理逻辑:

Swift
class RtmListener: NSObject, AgoraRtmClientDelegate {

    func rtmKit(_ rtmKit: AgoraRtmClientKit, didReceiveLinkStateEvent event: AgoraRtmLinkStateEvent) {
        // code
    }

    func rtmKit(_ rtmKit: AgoraRtmClientKit, didReceiveMessageEvent event: AgoraRtmMessageEvent) {
        // code
    }

    func rtmKit(_ rtmKit: AgoraRtmClientKit, didReceiveLockEvent event: AgoraRtmLockEvent) {
        // code
    }

    func rtmKit(_ rtmKit: AgoraRtmClientKit, didReceiveTopicEvent event: AgoraRtmTopicEvent) {
        // code
    }
    func rtmKit(_ rtmKit: AgoraRtmClientKit, didReceiveStorageEvent event: AgoraRtmStorageEvent) {
        // code
    }

    func rtmKit(_ rtmKit: AgoraRtmClientKit, tokenPrivilegeWillExpire channel: String?) {
        // code
    }
}

do {
    let config = AgoraRtmClientConfig(appId: "yourAppId", userId: "uniqueUserId")
    let listener = RtmListener()
    // Initializing the RTM client
    let rtmClient = try AgoraRtmClientKit(config, delegate: listener)
    if rtmClient != nil {
        print("RTM Client initialized successfully!")
    }
} catch let error {
    print("Failed to initialize RTM client. Error: \(error)")
}

删除事件监听

为避免内存泄漏、错误和异常(即空指针异常)引起的性能下降,声网建议你在不需要使用某个事件处理程序时对其进行注销。例如,如果不想关注 Lock 事件通知,删除对 didReceiveLockEvent 函数的定义即可。

事件通知类型

RTM 一共有 7 种类型事件,对应的有 7 种事件监听程序。你可以查看 API 参考的事件监听章节,了解每个事件监听程序传入参数的详细信息。

事件监听程序描述
didReceiveMessageEvent接收所有订阅的 Message Channel 中的消息通知或你加入的所有 Stream Channel 中订阅的 Topic 消息通知。事件负载数据中包含频道名称、频道类型、Topic 名称、事件发送者、消息负载数据类型等信息。
didReceivePresenceEvent接收所有订阅的 Message Channel 或者你加入的所有 Stream Channel 中远端用户的在线状态事件通知。事件负载数据中包含频道名称、频道类型、事件类型、事件发送者、用户临时状态数据等信息。
didReceiveTopicEvent接收加入的所有 Stream Channel 中 Topic 变更事件通知。事件负载数据中包含频道名称、事件类型、Topic 名称、事件发送者(即 Topic 详情)等信息。
didReceiveStorageEvent接收订阅的 Message Channel 及加入的 Stream Channel 中所有的 Channel Metadata 事件通知,以及所有订阅用户的 User Metadata 事件通知。事件负载数据中包含频道名称、频道类型、事件类型(即具体 Metadata 数据)等信息。
didReceiveLockEvent接收订阅的 Message Channel 及加入的 Stream Channel 中所有的 Lock 事件通知。事件负载数据中包含有频道名称、频道类型、事件类型、锁详情等信息。
didReceiveLinkStateEvent接收客户端网络连接状态变更的事件通知,包含变更前后的连接状态、服务类型、导致变更的操作类型、变更原因、频道列表等信息。
tokenPrivilegeWillExpire接收客户端 Token 将要过期的事件通知。
表格内容超出当前宽度,可横向滚动查看更多列。

完成事件监听处理程序后,你可以通过订阅频道或 Topic 来接收指定的 Message Channel 或 Stream Channel 中的消息和事件通知了。详见订阅 Message Channel 和订阅 Topic。