1.下载SDK
2.*
9000 订单支付成功
8000 正在处理中
4000 订单支付失败
6001 用户中途取消
6002 网络连接出错
*/
3.课堂上创建过程
打开终端:(1)pod search EaseMob (2)cd + 文件夹的名字 (3) vim Podfile 打开编辑器 (4)pod 'Easemob', '~> 2.1.4’(5)Esc (6)shift+; 输入wq (8) pod update(9)导入 #import <EaseMob.h>
4.创建一个有登陆和注册页的storyBoard
在AppDelegate.m里面写
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//初始化EaseMob
[[EaseMobsharedInstance] registerSDKWithAppKey:@"chenkai#bjs151251"apnsCertName:@"push"];
//启动完成
[[EaseMobsharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
//获取LoginAndRegister的Storyboard
UIStoryboard *loginStoryboard = [UIStoryboardstoryboardWithName:@"LoginAndRegist"bundle:nil];
//获取Storyboard里面的根视图控制器(模态到初始的Controller)
UIViewController *loginVC = [loginStoryboard instantiateInitialViewController];
//让loginStoryboard可见
[self.windowmakeKeyAndVisible];
//模态
[self.window.rootViewControllerpresentViewController:loginVC animated:YEScompletion:nil];
returnYES;
//初始化EaseMob
[[EaseMobsharedInstance] registerSDKWithAppKey:@"chenkai#bjs151251"apnsCertName:@"push"];
//启动完成
[[EaseMobsharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
//获取LoginAndRegister的Storyboard
UIStoryboard *loginStoryboard = [UIStoryboardstoryboardWithName:@"LoginAndRegist"bundle:nil];
//获取Storyboard里面的根视图控制器(模态到初始的Controller)
UIViewController *loginVC = [loginStoryboard instantiateInitialViewController];
//让loginStoryboard可见
[self.windowmakeKeyAndVisible];
//模态
[self.window.rootViewControllerpresentViewController:loginVC animated:YEScompletion:nil];
returnYES;
}
一.注册页面
#import "ViewController.h"
@interface ResistViewController : ViewController
///用户名
@property (weak, nonatomic) IBOutletUITextField *userNameField;
///密码
@property (weak, nonatomic) IBOutletUITextField *passwordField;
///确认密码
@property (weak, nonatomic) IBOutletUITextField *confirmField;
//点击注册的方法
@interface ResistViewController : ViewController
///用户名
@property (weak, nonatomic) IBOutletUITextField *userNameField;
///密码
@property (weak, nonatomic) IBOutletUITextField *passwordField;
///确认密码
@property (weak, nonatomic) IBOutletUITextField *confirmField;
//点击注册的方法
- (IBAction)didClickRegistButtonAction:(UIButton *)sender;}
.m文件
#import "ResistViewController.h"
#import <EaseMob.h>
@interfaceResistViewController ()
@end
@implementation ResistViewController
- (void)viewDidLoad {
[superviewDidLoad];
}
//点击注册的方法
- (IBAction)didClickRegistButtonAction:(UIButton *)sender {
if (self.userNameField.text.length > 0 && self.passwordField.text.length > 0) {
if ([self.passwordField.textisEqualToString:self.confirmField.text]) {
/*
//注册的同步方法
EMError *error = nil;
BOOL isSuccess = [[EaseMob sharedInstance].chatManager registerNewAccount:self.userNameField.text password:self.passwordField.text error:&error];
if (!isSuccess) {
NSLog(@"注册成功");
}
*/
//异步的注册方法(这里和同步的区别就是不用布尔值接收,用error)
[[EaseMobsharedInstance].chatManagerasyncRegisterNewAccount:self.userNameField.text password:self.passwordField.textwithCompletion:^(NSString *username, NSString *password, EMError *error) {
if (!error) {
NSLog(@"注册成功");
}
} onQueue:dispatch_get_main_queue() ];
}
@interfaceResistViewController ()
@end
@implementation ResistViewController
- (void)viewDidLoad {
[superviewDidLoad];
}
//点击注册的方法
- (IBAction)didClickRegistButtonAction:(UIButton *)sender {
if (self.userNameField.text.length > 0 && self.passwordField.text.length > 0) {
if ([self.passwordField.textisEqualToString:self.confirmField.text]) {
/*
//注册的同步方法
EMError *error = nil;
BOOL isSuccess = [[EaseMob sharedInstance].chatManager registerNewAccount:self.userNameField.text password:self.passwordField.text error:&error];
if (!isSuccess) {
NSLog(@"注册成功");
}
*/
//异步的注册方法(这里和同步的区别就是不用布尔值接收,用error)
[[EaseMobsharedInstance].chatManagerasyncRegisterNewAccount:self.userNameField.text password:self.passwordField.textwithCompletion:^(NSString *username, NSString *password, EMError *error) {
if (!error) {
NSLog(@"注册成功");
}
} onQueue:dispatch_get_main_queue() ];
}
}
二.登陆了页面
#import "LoginViewController.h"
#import <EaseMob.h>
@interfaceLoginViewController ()
///用户名
@property (weak, nonatomic) IBOutletUITextField *userNameField;
///密码
@property (weak, nonatomic) IBOutletUITextField *passworkField;
//登录按钮的点击方法
- (IBAction)didClickLoginButtonAction:(UIButton *)sender;
@end
@implementation LoginViewController
- (void)viewDidLoad {
[superviewDidLoad];
}
//登陆的按钮的点击方法
- (IBAction)didClickLoginButtonAction:(UIButton *)sender {
//判断
if (self.userNameField.text.length > 0 && self.passworkField.text.length > 0) {
//这里这里要设置infor.plist设置请求才可以登陆成功
/*
//同步的block方法
EMError *error = nil;
NSDictionary *loginInfo = [[EaseMob sharedInstance].chatManager loginWithUsername:self.userNameField.text password:self.passworkField.text error:&error ];
if (!error&&loginInfo) {
NSLog(@"登陆成功");
//登陆成功返回好友页面
[self dismissViewControllerAnimated:YES completion:nil];
}
*/
//异步的block方法
[[EaseMobsharedInstance].chatManagerasyncLoginWithUsername:self.userNameField.text password:self.passworkField.textcompletion:^(NSDictionary *loginInfo, EMError *error) {
if (!error) {
NSLog(@"登陆成功");
}
} onQueue:dispatch_get_main_queue() ];
//登陆成功返回好友页面
[selfdismissViewControllerAnimated:YEScompletion:nil];
}
}
#import <EaseMob.h>
@interfaceLoginViewController ()
///用户名
@property (weak, nonatomic) IBOutletUITextField *userNameField;
///密码
@property (weak, nonatomic) IBOutletUITextField *passworkField;
//登录按钮的点击方法
- (IBAction)didClickLoginButtonAction:(UIButton *)sender;
@end
@implementation LoginViewController
- (void)viewDidLoad {
[superviewDidLoad];
}
//登陆的按钮的点击方法
- (IBAction)didClickLoginButtonAction:(UIButton *)sender {
//判断
if (self.userNameField.text.length > 0 && self.passworkField.text.length > 0) {
//这里这里要设置infor.plist设置请求才可以登陆成功
/*
//同步的block方法
EMError *error = nil;
NSDictionary *loginInfo = [[EaseMob sharedInstance].chatManager loginWithUsername:self.userNameField.text password:self.passworkField.text error:&error ];
if (!error&&loginInfo) {
NSLog(@"登陆成功");
//登陆成功返回好友页面
[self dismissViewControllerAnimated:YES completion:nil];
}
*/
//异步的block方法
[[EaseMobsharedInstance].chatManagerasyncLoginWithUsername:self.userNameField.text password:self.passworkField.textcompletion:^(NSDictionary *loginInfo, EMError *error) {
if (!error) {
NSLog(@"登陆成功");
}
} onQueue:dispatch_get_main_queue() ];
//登陆成功返回好友页面
[selfdismissViewControllerAnimated:YEScompletion:nil];
}
}
@end
三.好友列表页面
#import "RosterTableController.h"
#import <EaseMob.h>
#import "ChatTableController.h"
@interfaceRosterTableController ()<IChatManagerDelegate>
///好友列表的属性
@property(nonatomic,strong)NSMutableArray *rosterArray;
@end
@implementation RosterTableController
//获取好友列表
- (void)reloadAllRosters{
EMError *error = nil;
NSArray *rosters = [[EaseMobsharedInstance].chatManagerfetchBuddyListWithError:&error];
if (!error) {
[self.rosterArrayremoveAllObjects];
[self.rosterArrayaddObjectsFromArray:rosters];
//刷新tableView
[self.tableViewreloadData];
NSLog(@"获取成功 -- %@",rosters);
}
}
- (void)viewDidAppear:(BOOL)animated{
[superviewDidAppear:animated];
//刷新好友列表
[selfreloadAllRosters];
}
- (void)viewDidLoad {
[superviewDidLoad];
//初始化好友数组
self.rosterArray = [NSMutableArraynew];
[selfreloadAllRosters];
//添加代理
[[EaseMobsharedInstance].chatManageraddDelegate:selfdelegateQueue:dispatch_get_main_queue()];
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
returnself.rosterArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Roster"forIndexPath:indexPath];
EMBuddy *roster = self.rosterArray[indexPath.row];
cell.textLabel.text = roster.username;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
returnYES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//删除好友
EMBuddy *buddy = self.rosterArray[indexPath.row];
EMError *error = nil;
//removeFromRemote:是否从对方的好友删除 [[EaseMobsharedInstance].chatManagerremoveBuddy:buddy.usernameremoveFromRemote:YESerror:&error ]; //从数组删除 [self.rosterArrayremoveObject:buddy]; if (!error) { NSLog(@"删除成功"); } //先删除数据再操作UI [tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationFade]; } elseif (editingStyle == UITableViewCellEditingStyleInsert) { } }- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifierisEqualToString:@"Chat"]) { //传值 //选中的行数 NSIndexPath *indexPath = [self.tableViewindexPathForSelectedRow]; EMBuddy *buddy = self.rosterArray[indexPath.row]; ChatTableController *chatTC = [segue destinationViewController]; chatTC.buddy = buddy; }}//接收到好友请求- (void)didReceiveBuddyRequest:(NSString *)username message:(NSString *)message{ UIAlertController *alertC = [UIAlertControlleralertControllerWithTitle:@"好友请求"message:message preferredStyle:(UIAlertControllerStyleAlert)]; //接收好友 UIAlertAction *accept = [UIAlertActionactionWithTitle:@"接收"style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) { EMError *error = nil; BOOL success = [[EaseMobsharedInstance] .chatManageracceptBuddyRequest:username error:&error]; if (!error && success) { NSLog(@"接收好友请求"); } }]; [alertC addAction:accept]; //拒绝好友 UIAlertAction *refuse = [UIAlertActionactionWithTitle:@"拒绝"style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) { EMError *error = nil; BOOL success = [[EaseMobsharedInstance].chatManagerrejectBuddyRequest:username reason:@"不是人类"error:&error ]; if (!error && success) { NSLog(@"拒绝好友请求"); } }]; [alertC addAction:refuse];
#import <EaseMob.h>
#import "ChatTableController.h"
@interfaceRosterTableController ()<IChatManagerDelegate>
///好友列表的属性
@property(nonatomic,strong)NSMutableArray *rosterArray;
@end
@implementation RosterTableController
//获取好友列表
- (void)reloadAllRosters{
EMError *error = nil;
NSArray *rosters = [[EaseMobsharedInstance].chatManagerfetchBuddyListWithError:&error];
if (!error) {
[self.rosterArrayremoveAllObjects];
[self.rosterArrayaddObjectsFromArray:rosters];
//刷新tableView
[self.tableViewreloadData];
NSLog(@"获取成功 -- %@",rosters);
}
}
- (void)viewDidAppear:(BOOL)animated{
[superviewDidAppear:animated];
//刷新好友列表
[selfreloadAllRosters];
}
- (void)viewDidLoad {
[superviewDidLoad];
//初始化好友数组
self.rosterArray = [NSMutableArraynew];
[selfreloadAllRosters];
//添加代理
[[EaseMobsharedInstance].chatManageraddDelegate:selfdelegateQueue:dispatch_get_main_queue()];
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
returnself.rosterArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Roster"forIndexPath:indexPath];
EMBuddy *roster = self.rosterArray[indexPath.row];
cell.textLabel.text = roster.username;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
returnYES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//删除好友
EMBuddy *buddy = self.rosterArray[indexPath.row];
EMError *error = nil;
//removeFromRemote:是否从对方的好友删除 [[EaseMobsharedInstance].chatManagerremoveBuddy:buddy.usernameremoveFromRemote:YESerror:&error ]; //从数组删除 [self.rosterArrayremoveObject:buddy]; if (!error) { NSLog(@"删除成功"); } //先删除数据再操作UI [tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationFade]; } elseif (editingStyle == UITableViewCellEditingStyleInsert) { } }- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifierisEqualToString:@"Chat"]) { //传值 //选中的行数 NSIndexPath *indexPath = [self.tableViewindexPathForSelectedRow]; EMBuddy *buddy = self.rosterArray[indexPath.row]; ChatTableController *chatTC = [segue destinationViewController]; chatTC.buddy = buddy; }}//接收到好友请求- (void)didReceiveBuddyRequest:(NSString *)username message:(NSString *)message{ UIAlertController *alertC = [UIAlertControlleralertControllerWithTitle:@"好友请求"message:message preferredStyle:(UIAlertControllerStyleAlert)]; //接收好友 UIAlertAction *accept = [UIAlertActionactionWithTitle:@"接收"style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) { EMError *error = nil; BOOL success = [[EaseMobsharedInstance] .chatManageracceptBuddyRequest:username error:&error]; if (!error && success) { NSLog(@"接收好友请求"); } }]; [alertC addAction:accept]; //拒绝好友 UIAlertAction *refuse = [UIAlertActionactionWithTitle:@"拒绝"style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) { EMError *error = nil; BOOL success = [[EaseMobsharedInstance].chatManagerrejectBuddyRequest:username reason:@"不是人类"error:&error ]; if (!error && success) { NSLog(@"拒绝好友请求"); } }]; [alertC addAction:refuse];
//模态
[selfpresentViewController:alertC animated:YEScompletion:nil];
}
四.添加好友界面
#import "AddViewController.h"
#import <EaseMob.h>
@interfaceAddViewController ()
///好友的用户名
@property (weak, nonatomic) IBOutletUITextField *userNameField;
- (IBAction)didClickAddBUttonAction:(UIButton *)sender;
@end
@implementation AddViewController
- (void)viewDidLoad {
[superviewDidLoad];
}
//点击添加按钮的方法
- (IBAction)didClickAddBUttonAction:(UIButton *)sender {
if (self.userNameField.text.length > 0) {
//添加好友
EMError *error = nil;
BOOL isSuccess = [[EaseMobsharedInstance].chatManageraddBuddy:self.userNameField.textmessage:@"我想加你为好友"error:&error ];
if (!error && isSuccess) {
NSLog(@"发送好友请求成功");
}
}
#import <EaseMob.h>
@interfaceAddViewController ()
///好友的用户名
@property (weak, nonatomic) IBOutletUITextField *userNameField;
- (IBAction)didClickAddBUttonAction:(UIButton *)sender;
@end
@implementation AddViewController
- (void)viewDidLoad {
[superviewDidLoad];
}
//点击添加按钮的方法
- (IBAction)didClickAddBUttonAction:(UIButton *)sender {
if (self.userNameField.text.length > 0) {
//添加好友
EMError *error = nil;
BOOL isSuccess = [[EaseMobsharedInstance].chatManageraddBuddy:self.userNameField.textmessage:@"我想加你为好友"error:&error ];
if (!error && isSuccess) {
NSLog(@"发送好友请求成功");
}
}
}
五.聊天页面
.h文件
#import <UIKit/UIKit.h>
#import <EaseMob.h>
@interface ChatTableController : UITableViewController
///会话的TextField
@property (weak, nonatomic) IBOutletUITextField *chatField;
///好友属性
@property(nonatomic,strong)EMBuddy *buddy;
#import <EaseMob.h>
@interface ChatTableController : UITableViewController
///会话的TextField
@property (weak, nonatomic) IBOutletUITextField *chatField;
///好友属性
@property(nonatomic,strong)EMBuddy *buddy;
.m文件 这里需要用到一个类
#import "ChatTableController.h"
#import "MessageBody.h"
@interfaceChatTableController ()<IChatManagerDelegate>
///消息列表
@property(nonatomic,strong)NSMutableArray *messageArray;
//发送消息
- (IBAction)sendMessage:(UIBarButtonItem *)sender;
@end
@implementation ChatTableController
- (void)viewDidLoad {
[superviewDidLoad];
self.messageArray = [NSMutableArraynew];
EMConversation *conversation = [[EaseMobsharedInstance].chatManagerconversationForChatter:self.buddy.usernameconversationType:eConversationTypeChat ];
//接收消息代理执行
conversation.enableUnreadMessagesCountEvent = YES;
//添加代理队列
[[EaseMobsharedInstance].chatManageraddDelegate:selfdelegateQueue:dispatch_get_main_queue()];
//展示标题
self.title = self.buddy.username;
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
returnself.messageArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Chat"forIndexPath:indexPath];
EMMessage *message = self.messageArray[indexPath.row];
if ([message.toisEqualToString:self.buddy.username]) {
cell.textLabel.text = @"";
MessageBody *body = message.messageBodies[0];
//字符 对象
EMChatText *textBody = [body chatObject];
cell.detailTextLabel.text = textBody.text;
}else{
MessageBody *body = message.messageBodies[0];
//字符 对象
EMChatText *textBody = [body chatObject];
cell.textLabel.text = textBody.text;
cell.detailTextLabel.text = @"";
}
return cell;}//刷新消息记录- (void)reloadAllMessages{ //通过两人的会话取聊天记录 EMConversation *conversation = [[EaseMobsharedInstance].chatManagerconversationForChatter:self.buddy.usernameconversationType:eConversationTypeChat]; NSArray *messages = [conversation loadAllMessages]; if (messages.count > 0) { [self.messageArrayremoveAllObjects]; [self.messageArrayaddObjectsFromArray:messages]; //滚动到最后一条 NSIndexPath *indexPath = [NSIndexPathindexPathForRow:self.messageArray.count - 1inSection:0]; //刷新tableView [self.tableViewreloadData]; [self.tableViewscrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottomanimated:YES]; }}//接收到消息- (void)didReceiveMessage:(EMMessage *)message{ NSLog(@"接收到消息"); [selfreloadAllMessages];}//接收离线消息- (void)didReceiveOfflineMessages:(NSArray *)offlineMessages{ NSLog(@"接收离线消息"); [selfreloadAllMessages];}//将要发送消息- (void)willSendMessage:(EMMessage *)message error:(EMError *)error{ NSLog(@"将要发送消息");}//消息发送成功- (void)didSendMessage:(EMMessage *)message error:(EMError *)error{ NSLog(@"消息发送成功"); [selfreloadAllMessages];}- (IBAction)sendMessage:(UIBarButtonItem *)sender { //创建文本消息 EMChatText *chatText = [[EMChatTextalloc] initWithText:self.chatField.text]; /* 这是错误的// //创建MessageBody// MessageBody *body = [[MessageBody alloc] initWithChatObject:chatText];// body.messageBodyType = eMessageBodyType_Text; */ EMTextMessageBody *body = [[EMTextMessageBodyalloc]initWithChatObject:chatText]; //创建message对象 EMMessage *message = [[EMMessagealloc] initWithReceiver:self.buddy.usernamebodies:@[body]]; EMError *error = nil; [[EaseMobsharedInstance].chatManagersendMessage:message progress:nilerror:&error]; if (!error) { NSLog(@"消息发送成功"); [selfreloadAllMessages]; } }
#import "MessageBody.h"
@interfaceChatTableController ()<IChatManagerDelegate>
///消息列表
@property(nonatomic,strong)NSMutableArray *messageArray;
//发送消息
- (IBAction)sendMessage:(UIBarButtonItem *)sender;
@end
@implementation ChatTableController
- (void)viewDidLoad {
[superviewDidLoad];
self.messageArray = [NSMutableArraynew];
EMConversation *conversation = [[EaseMobsharedInstance].chatManagerconversationForChatter:self.buddy.usernameconversationType:eConversationTypeChat ];
//接收消息代理执行
conversation.enableUnreadMessagesCountEvent = YES;
//添加代理队列
[[EaseMobsharedInstance].chatManageraddDelegate:selfdelegateQueue:dispatch_get_main_queue()];
//展示标题
self.title = self.buddy.username;
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
returnself.messageArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Chat"forIndexPath:indexPath];
EMMessage *message = self.messageArray[indexPath.row];
if ([message.toisEqualToString:self.buddy.username]) {
cell.textLabel.text = @"";
MessageBody *body = message.messageBodies[0];
//字符 对象
EMChatText *textBody = [body chatObject];
cell.detailTextLabel.text = textBody.text;
}else{
MessageBody *body = message.messageBodies[0];
//字符 对象
EMChatText *textBody = [body chatObject];
cell.textLabel.text = textBody.text;
cell.detailTextLabel.text = @"";
}
return cell;}//刷新消息记录- (void)reloadAllMessages{ //通过两人的会话取聊天记录 EMConversation *conversation = [[EaseMobsharedInstance].chatManagerconversationForChatter:self.buddy.usernameconversationType:eConversationTypeChat]; NSArray *messages = [conversation loadAllMessages]; if (messages.count > 0) { [self.messageArrayremoveAllObjects]; [self.messageArrayaddObjectsFromArray:messages]; //滚动到最后一条 NSIndexPath *indexPath = [NSIndexPathindexPathForRow:self.messageArray.count - 1inSection:0]; //刷新tableView [self.tableViewreloadData]; [self.tableViewscrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottomanimated:YES]; }}//接收到消息- (void)didReceiveMessage:(EMMessage *)message{ NSLog(@"接收到消息"); [selfreloadAllMessages];}//接收离线消息- (void)didReceiveOfflineMessages:(NSArray *)offlineMessages{ NSLog(@"接收离线消息"); [selfreloadAllMessages];}//将要发送消息- (void)willSendMessage:(EMMessage *)message error:(EMError *)error{ NSLog(@"将要发送消息");}//消息发送成功- (void)didSendMessage:(EMMessage *)message error:(EMError *)error{ NSLog(@"消息发送成功"); [selfreloadAllMessages];}- (IBAction)sendMessage:(UIBarButtonItem *)sender { //创建文本消息 EMChatText *chatText = [[EMChatTextalloc] initWithText:self.chatField.text]; /* 这是错误的// //创建MessageBody// MessageBody *body = [[MessageBody alloc] initWithChatObject:chatText];// body.messageBodyType = eMessageBodyType_Text; */ EMTextMessageBody *body = [[EMTextMessageBodyalloc]initWithChatObject:chatText]; //创建message对象 EMMessage *message = [[EMMessagealloc] initWithReceiver:self.buddy.usernamebodies:@[body]]; EMError *error = nil; [[EaseMobsharedInstance].chatManagersendMessage:message progress:nilerror:&error]; if (!error) { NSLog(@"消息发送成功"); [selfreloadAllMessages]; } }
@end
六.创建的类
.h文件
#import <Foundation/Foundation.h>
#import <EaseMob.h>
@interface MessageBody : NSObject<IEMMessageBody>
@property (nonatomic, assign) MessageBodyType messageBodyType;
@property (nonatomic, strong, readonly) id<IEMChatObject> chatObject;
@property (nonatomic, weak) EMMessage *message;
- (id)initWithChatObject:(id<IEMChatObject>)aChatObject;
#import <EaseMob.h>
@interface MessageBody : NSObject<IEMMessageBody>
@property (nonatomic, assign) MessageBodyType messageBodyType;
@property (nonatomic, strong, readonly) id<IEMChatObject> chatObject;
@property (nonatomic, weak) EMMessage *message;
- (id)initWithChatObject:(id<IEMChatObject>)aChatObject;
@end
.m文件(这里是因为签订了协议必须实现这个方法)
#import "MessageBody.h"
@implementation MessageBody
- (id)initWithChatObject:(id<IEMChatObject>)aChatObject{
returnnil;
}
@implementation MessageBody
- (id)initWithChatObject:(id<IEMChatObject>)aChatObject{
returnnil;
}
@end