首先說明:樓主用的是環信3.x的,不過可能2.x也差不多(我是這么想的)
最近項目中需要用到環信透傳消息,按照正常的套路(對,沒錯看官方文檔),可是結果并不是很明顯,文檔中只寫了一部分,然后各種查資料。還是沒有效果,不過后來大神回來了,然后一切問題都解決了。好不說了,上代碼。
創建消息
//需要導入一些頭文件,這里就不詳細說明了
- (void)sendCmdMessage{
EMCmdMessageBody *body = [[EMCmdMessageBody alloc] initWithAction:<#發送的消息內容#>];
NSString *from = <#發送者#>;
//生成Message
/**
converstionID : 獲取接收對象ID
from : 發送方
to : 接收對象
boby : 發送內容
ext : 擴展消息(可以為空)
converstionID == to
*/
//以手機號為例
EMMessage *message = [[EMMessage alloc] initWithConversationID:@"123456789" from:from to:@"123456789" body:body ext:nil];
message.chatType = EMChatTypeChat;// 設置為單聊消息
//message.chatType = EMChatTypeGroupChat;// 設置為群聊消息
//message.chatType = EMChatTypeChatRoom;// 設置為聊天室消息
[self _sendMessage:message];//上面的只是在創建消息,這一步才是發送
}
發送消息
發送消息之前,先添加一個屬性
@property(nonatomic,strong)EaseMessageViewController *easeMessage;
事先說明: _refreshAfterSentMessage:
方法是環信官方SDK提供的,位置是在 EaseMessageViewController.m
中 ,大概1783行左右。這是對消息內容的格式方法(我是這么理解的)。最簡單粗暴的方法就是,把這個方法添加到EaseMessageViewController.h
中,讓外部可以訪問(反正我是這么做的)
- (void)_sendMessage:(EMMessage *)message{
[[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:^(EMMessage *aMessage, EMError *aError) {
[easeMessage _refreshAfterSentMessage:aMessage];
}];
}
恭喜你透傳消息已經發送出去了,接下來看看接收透傳消息
首先導入頭文件,添加代理協議(建議接收消息寫到視圖根控制器中)
#import "EMCDDeviceManager+ProximitySensor.h"
//可能還需要別的頭文件,請自己添加
@interface ViewController : UIViewController <EMChatManagerDelegate,EMCDDeviceManagerDelegate,EMChatroomManagerDelegate>
在 .m
的viewDidLoad
中初始化一些方法
[EMCDDeviceManager sharedInstance].delegate = self;
[[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
[[EMClient sharedClient].roomManager addDelegate:self delegateQueue:nil];
接收消息
- (void)didReceiveCmdMessages:(NSArray *)aCmdMessages
{
NSLog(@"接收到環信透傳消息");
}
請注意還有最關鍵的一步,開啟近距離傳感器(監聽透傳消息)
在viewWillAppear
或viewDidLoad
中添加以下代碼
[[EMCDDeviceManager sharedInstance] enableProximitySensor];//個人建議在 viewwillAppear 中添加
完成接收消息
如果接收不到消息,請檢查環信是否已經登錄(對,你猜的不錯,我犯過這樣的錯誤)