这里我们用融云来实现私聊功能,首先创建小微信的应用,其次在IM服务中选择API调试;补充userId和name:
选择提交得到如下结果:
并初始化appkey与测试连接:
//初始化appkey
RCIM.sharedRCIM().initWithAppKey("8luwapkvu3y4l")
//用token测试链接
RCIM.sharedRCIM().connectWithToken("KVQA8zlsxifN+8wBYfrdzFGHWMnd1yenzzdqyv6OVpxClvCAxJwi2ZHpNzOeray8pGD1uBAhM8sXBEFU+k/VLQ==", success: {
(_)-> Void in
print("连接成功!")
})
}, error: { (_) -> Void in
print("连接失败!")
}){
()->Void in
print("Token不正确,或已经失效!")
}
}
然后我们需要设置当前信息:
let currentUserInfo = RCUserInfo(userId: "xiong1", name:"熊1", portrait:"http://user.qzone.qq.com/1159565251/4")
RCIMClient.sharedRCIMClient().currentUserInfo = currentUserInfo
添加私聊功能;新建一个RCConversationViewController,并添加如下代码:
self.setMessageAvatarStyle(._USER_AVATAR_CYCLE)
self.targetId = "xiong2"
self.userName = "熊2"
self.conversationType = .ConversationType_PRIVATE
self.title = "与" + self.userName + "对话中"
在链接服务器的时候,由于UI界面和后台需要分开;故需要在该段代码调用闭包返回的时候,让其回到主线程:
func connectserver(completion:()->Void){
//初始化appkey
RCIM.sharedRCIM().initWithAppKey("8luwapkvu3y4l")
//用token测试链接
RCIM.sharedRCIM().connectWithToken("WxdIW9mMaXG065raJ0F6T2HUWf58pJ6ADt3rlcK4W2GMHZgdePTYxizmS8RsC0e4NO6WR9TdempORT15+jUD9g==", success: {
(_)-> Void in
print("连接成功!")
let currentUserInfo = RCUserInfo(userId: "xiong1", name:"熊1", portrait:"http://user.qzone.qq.com/1159565251/4")
RCIMClient.sharedRCIMClient().currentUserInfo = currentUserInfo
dispatch_async(dispatch_get_main_queue(), {
() -> Void in
completion()
})
}, error: { (_) -> Void in
print("连接失败!")
}){
()->Void in
print("Token不正确,或已经失效!")
}
}
也可以添加多个用户信息:
func getUserInfoWithUserId(userId: String!, completion: ((RCUserInfo!) -> Void)!) {
let userInfo = RCUserInfo()
userInfo.userId = userId
switch userId {
case "xiong":
userInfo.name = "熊"
userInfo.portraitUri = "http://photo.renren.com/photo/287307670/album-321349882/v7#photo/287307670/8023349882"
case "xiong1":
userInfo.name = "熊1"
userInfo.portraitUri = "http://photo.renren.com/photo/287307670/album-321349882/v7#photo/287307670/7991476622"
default:
print("无此用户")
}
return completion(userInfo)
}
并在ConversationListViewController中添加下述代码:
appDelegate?.connectserver({
() -> Void in
self.setDisplayConversationTypes([
RCConversationType.ConversationType_APPSERVICE.rawValue,
RCConversationType.ConversationType_CHATROOM.rawValue,
RCConversationType.ConversationType_CUSTOMERSERVICE.rawValue,
RCConversationType.ConversationType_DISCUSSION.rawValue,
RCConversationType.ConversationType_GROUP.rawValue,
RCConversationType.ConversationType_PRIVATE.rawValue,
RCConversationType.ConversationType_PUBLICSERVICE.rawValue,
RCConversationType.ConversationType_SYSTEM.rawValue
])
self.refreshConversationTableViewIfNeeded()
})
可以显示出效果如下: