首先是登录问题,
第一要先初始化环信,关于环信的第一步。一般来说写在AppDelegate里面。
extension AppDelegate:EMClientDelegate,EMChatManagerDelegate {
fileprivate func setupemChat(){
//添加EMClient的代理
EMClient.shared().add(self, delegateQueue: nil)
let options = EMOptions.init(appkey: EMAppKey)
options?.apnsCertName = EMapnsCertName
let error = EMClient.shared().initializeSDK(with: options)
if error == nil{
print("初始化成功")
}
EMClient.shared().chatManager.add(self, delegateQueue: nil)
}
}第二步,才是登录
//环信登录
func emChat(){
// 1. 模拟异步
DispatchQueue.global().async {
let username = userDefault.string(forKey: easemob_username)
let password = userDefault.string(forKey: easemob_password)
//用于判断是否开启了自动登录
let isAutoLogin = EMClient.shared().options.isAutoLogin
if !isAutoLogin {
if username != "" && username != nil && password != "" && password != nil{
let error = EMClient.shared().login(withUsername: username, password: password)
if error == nil{
print("登录成功")
//自动登录(内部会把用户名和密码保存到用户的偏好设置里)
EMClient.shared().options.isAutoLogin = true
}else{
print("登录失败")
print(error.debugDescription)
}
}
}
}
}
第三步,如果实现了EMClientDelegate代理环信会走这两个代理方法。(一定要写前面黄色背景那句话)
extension AppDelegate:EMClientDelegate,EMChatManagerDelegate {
//EMClientDelegate中的方法,如果发生自动登录,会有以下回调
func autoLoginDidCompleteWithError(_ aError: EMError!) {
print("autoLoginDidCompleteWithError - \(aError)")
}
//EMClientDelegate中的方法,当前登录账号在其它设备登录时会接收到此回调
func userAccountDidLoginFromOtherDevice() {
SVProgressHUD.showError(withStatus: "您的账号在其他设备上登录了~")
GeneralTools.share.loginout()
appDelegate.window?.rootViewController = DDNavigationController(rootViewController: DDOauthViewController())
}
}
关于新消息
感觉没啥好说的,初始化环信后,走上面浅黄色那句话,然后实现EMChatManagerDelegate代理方法
//收到环信新消息提示
func messagesDidReceive(_ aMessages: [Any]!) {
notice.post(name: NotifyMessageMsg, object: nil)
}