环信3.0ios客户端的集成(十四)

版本记录

版本号 时间
V1.0 2017.06.25

前言

很多app种都集成环信做第三方信息通讯工具,这里我们就看一下环信的主要功能和集成方法。先给出环信3.0的地址。
感兴趣的可以参考:
1. 环信ios客户端的集成(一)
2. 环信ios客户端的集成(二)
3. 环信ios客户端的集成(三)
4. 环信ios客户端的集成(四)
5. 环信ios客户端的集成(五)
6. 环信ios客户端的集成(六)
7. 环信ios客户端的集成(七)
8. 环信ios客户端的集成(八)
9. 环信ios客户端的集成(九)
10. 环信ios客户端的集成(十)
11. 环信ios客户端的集成(十一)
12. 环信ios客户端的集成(十二)
13. 环信ios客户端的集成(十三)
这一篇主要说一下环信的 基于环信3.0的及时通讯在具体工程上的应用

一、环信的集成

工程里我使用的是pod进行集成的,环信有两个版本,一个版本是带语音功能的,另外一个版本是不带语音功能的,我集成的是带语音功能的,方便以后项目需求有所扩展,目前的项目还是用不到语音的。

pod 'Hyphenate'

下面看一下集成后的环信文档组织结构。

代码组织结构-1
代码组织架构-2

二、环信的使用

下面就以具体工程为例进行具体说一下环信的集成。

单例类管理环信状态

下面新建立一个环信单例类,在这个类里的方法主要就是管理登录状态,以及几个代理的回调,包括是否登录的代理回调、是否收到消息的代理回调以及消息是否送达和读取的回调等。
下面看代码。

//这个头文件继承自NSObject
#import "JJBaseModel.h"

@interface JJMessageDataTool : NSObject <EMClientDelegate, EMChatManagerDelegate>

//单例
+ (instancetype)shareMessageTool;

//登录
- (void) loginEMClient;

//退出登陆
- (void) layoutEMClient;

//获取登陆状态
- (BOOL) getLoginStatus;

@end

这里的头文件,没有暴露出是否读取和有消息的回调接口,后面会加上该接口。

#import "JJMessageDataTool.h"

@interface JJMessageDataTool () <EMClientDelegate, EMChatManagerDelegate>

@property (nonatomic, strong) EMClient *client;

@end

@implementation JJMessageDataTool

#pragma mark - Class Public Function

+ (instancetype)shareMessageTool
{
    static JJMessageDataTool *tool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[JJMessageDataTool alloc] init];
        EMOptions *options = [EMOptions optionsWithAppkey:@"你的环信appKey"];
        [[EMClient sharedClient] initializeSDKWithOptions:options];
        [[EMClient sharedClient] addDelegate:tool delegateQueue:nil];   //回调代理
        [[EMClient sharedClient].chatManager addDelegate:tool delegateQueue:nil];
    });
    return tool;
}

//自动登录回调

- (void)connectionStateDidChange:(EMConnectionState)aConnectionState 
{
    if (aConnectionState == EMConnectionConnected) {
        NSLog(@"环信已连接");
    } 
    else {
        NSLog(@" 环信连接断开");
    }
}

//会话列表发生变化
- (void)conversationListDidUpdate:(NSArray *)aConversationList 
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kJJPrivateMessageListChat object:aConversationList];
}

//收到消息
- (void)messagesDidReceive:(NSArray *)aMessages 
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kJJPrivateMessageChat object:aMessages];
}

//消息已读
- (void)messagesDidRead:(NSArray *)aMessages 
{

}

//消息已送达
- (void)messagesDidDeliver:(NSArray *)aMessages 
{

}

//登录
- (void) loginEMClient 
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if ([JJConfig getOwnID]) {
            //登录
            EMError *loginError = [[EMClient sharedClient] loginWithUsername:[JJConfig getOwnID] password:[JJConfig getEasePassword]];
            if (!loginError) {
                [[EMClient sharedClient].options setIsAutoLogin:YES];
                NSLog(@"环信登录成功!!!");
            }
            else {
                NSLog(@"环信登录失败,失败原因是%@",loginError.errorDescription);
            }
        }
    });
}

//退出登陆
- (void) layoutEMClient 
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[EMClient sharedClient] logout:YES completion:^(EMError *aError) {
            NSLog(@"环信已退出登陆");
        }];
    });
}

//获取登陆状态
- (BOOL) getLoginStatus 
{
    if ([EMClient sharedClient].currentUsername && [EMClient sharedClient].currentUsername.length > 0) {
        return YES;
    }
    return NO;
}

@end

这个是个工具在appDidFinishLaunching的时候就要初始化,与app生命周期相同,全局进行监控和管理。

服务端和客户端的分工

我们这里继承环信需要服务端的参与,但是参与的不是很多,主要如下:

  • 服务端负责返回给我们环信的密码,注册是在服务端做的;
  • 客户端进行其他方面的UI以及逻辑控制。
    我们客户端向自己的服务器请求,获取环信的密码。

这里客户端有几点要主要注意:

  • 我们这边是登录的时候,服务器会返回给我们环信密码,而我们登录分为三方以及手机号登录,因此,要在这两个地方保存返回的环信密码,保存在沙盒。
userInfo.easePasswordStr = [dataDict objectForKey:@"easemobPassword"];

//环信登录,在本app登录成功后登录环信
[[ZBMessageDataTool shareMessageTool] loginEMClient];

将这个字典在两处登录成功以后保存,然后以字典的形式保存在偏好设置里面。

但是app在启动方法里面- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions也要判断登录状态,如果没有登录,要进行登录,同样是用上面的单例进行登录管理工作。

1. AppDelegate.m
    if ([[JMessageDataTool shareMessageTool] getLoginStatus]) {
        //已自动登录
        NSLog(@"环信自动登录");
    } 
    else {
        [[JJMessageDataTool shareMessageTool] loginEMClient];
    }

登录好了,下面就是客户端的工作了。

客户端的实现

下面就是我们的重头戏,那就是客户端的实现了,前面登录逻辑以及其他的集成管理都做好了,下面就是客户端的事了。我们点击用户头像,然后在点击发消息的按钮,就可以发送消息了。

下面先准备下数据。

- (void)contactChatButtonDidClick:(JJUIButton *)button
{
    NSLog(@"发送消息的按钮被点击了");
    
    JJChatViewController *chatVC = [[JJChatViewController alloc] init];
    JJMessageModel *messageModel = [[JJMessageModel alloc] init];
    messageModel.toUserName = self.userModel.userNickname?:@"";
    messageModel.uname = [JJConfig getOwnNicename]?:@"";
    messageModel.uhead = [JJConfig myProfile].avatar?:@"";
    messageModel.toUserHead = self.userModel.userAvatar?:@"";
    chatVC.conversationId = [NSString stringWithFormat:@"%ld", self.userModel.userId];
    chatVC.messageModel = messageModel;
    chatVC.title = self.userModel.userNickname;

    [self.navigationController pushViewController:chatVC animated:YES];
}

这里JJChatViewController是聊天室,JJMessageModel这个是聊天数据模型。下面看一下数据模型。

#import <Foundation/Foundation.h>
#import "JJMessageChatModel.h"

//私信模型

@interface JJMessageModel : JJBaseModel

@property (nonatomic, copy) NSString *lastMessage;                      //最后一条消息
@property (nonatomic, copy) NSString *uname;                            //发送者昵称
@property (nonatomic, copy) NSString *uhead;                            //发送者头像
@property (nonatomic, copy) NSString *toUserName;                       //接受者名称
@property (nonatomic, copy) NSString *toUserHead;                       //接受者头像
@property (nonatomic, copy) NSString *un_read_num;                      //未读数量
@property (nonatomic, copy) NSString *imgPath;
@property (nonatomic, copy) NSString *conversationId;

+ (instancetype)shareMessageModel;

@end

下面我们看一下聊天室JJChatViewController

1. JJChatViewController.h

#import "JJBaseVC.h"

@class JJMessageModel;

//聊天界面
@interface JJChatViewController : JJBaseVC

@property (nonatomic, strong) JJMessageModel *messageModel;
@property (nonatomic, copy) NSString *conversationId;

@end

2. JJChatViewController.m
#import "JJChatViewController.h"
#import "JJMessageChatCell.h"
#import "JJMessageModel.h"
#import "JJMessageDataTool.h"
#import "JJPersonCenterContainVC.h"

@interface JJChatViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, EMChatManagerDelegate, UIImagePickerControllerDelegate, JJMessageChatCellDelegate, JJChatSendCollectionDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <JJChatModelFrame *>*chatArray;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UIView *sendView;
@property (nonatomic, assign) long long lastTime;
@property (nonatomic, assign) CGFloat kbHeight;
@property (nonatomic, strong) JJUIView *backView;
@property (nonatomic, strong) UIImage *sendImage;

@end

@implementation JJChatViewController

static NSString * const JJMessageChatCellID = @"JJMessageChatCellID";

#pragma mark - Override Base Function

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (![[JJMessageDataTool shareMessageTool] getLoginStatus]) {
        [[JJMessageDataTool shareMessageTool] loginEMClient];
    }
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F1F2F3"];

    self.chatArray = [NSMutableArray array];
    //创建回话
    [self creatSession];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kJJCommonScreenWidth, kJJCommonScreenHeight - 50) style:UITableViewStylePlain];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor colorWithHexString:@"#F1F2F3"];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[JMessageChatCell class] forCellReuseIdentifier:JJMessageChatCellID];
    
    self.sendView.frame = CGRectMake(0, kJJCommonScreenHeight - 50, kJJCommonScreenWidth, 50);
    self.sendView.backgroundColor = [UIColor whiteColor];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceivedMessages:) name:kJJPrivateMessageChat object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated 
{
    [super viewWillAppear:animated];

    self.navigationController.navigationBarHidden = NO;
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    NSLog(@"%s",__FUNCTION__);
}

#pragma mark - Object Private Function

- (UIView *)sendView
{
    if (!_sendView) {
        _sendView = [[UIView alloc] init];
        [self.view addSubview:_sendView];
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 5, kJJCommonScreenWidth - 70, 40)];
        [_sendView addSubview:_textField];
        _textField.borderStyle = UITextBorderStyleRoundedRect;
        _textField.placeholder = @"输入新消息";
        _textField.returnKeyType = UIReturnKeyDone;
        _textField.delegate = self;
        
        //加号按钮
        JJUIButton *moreButton = [JJUIButton buttonWithType:UIButtonTypeCustom];
        [moreButton setImage:[UIImage imageNamed:@"chat_more"] forState:UIControlStateNormal];
        [moreButton addTarget:self action:@selector(moreButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [_sendView addSubview:moreButton];
        
        [moreButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_textField);
            make.left.equalTo(_textField.mas_right).offset(10.0);
            make.width.height.equalTo(@(CGRectGetHeight(_textField.frame)));
        }];
    }
    return _sendView;
}

- (void)endEdit
{
    if (self.textField.text.length == 0) {
        return;
    }
    
    //发送出去
    [self sendMessageWithMessage:self.textField.text andType:nil];
    self.textField.text = @"";
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    self.kbHeight = kbHeight;
    // 取得键盘的动画时间,这样可以在视图上移的时候更连贯
    NSTimeInterval duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        //按钮上移
        self.tableView.frame = CGRectMake(0, 0, kJJCommonScreenWidth, kJJCommonScreenHeight - 50 - kbHeight);
        self.sendView.frame = CGRectMake(0, kJJCommonScreenHeight - 50 - kbHeight, kJJCommonScreenWidth, 50);
        if (self.tableView.contentSize.height > self.tableView.height) {
            [self.tableView scrollToBottom];
        }
    } completion:^(BOOL finished) {
        
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    // 取得键盘的动画时间,这样可以在视图上移的时候更连贯
    NSTimeInterval duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
        self.tableView.frame = CGRectMake(0, 0, kJJCommonScreenWidth, kJCommonScreenHeight - 50);
        self.sendView.frame = CGRectMake(0, kJJCommonScreenHeight - 50, kJJCommonScreenWidth, 50);
        if (self.tableView.contentSize.height > self.tableView.height) {
            [self.tableView scrollToBottom];
        }
    } completion:^(BOOL finished) {
        
    }];
}

//判断前后时间是否一致

- (BOOL)timeIsEqualInOneHour:(long long )comStrTime
{
    NSString *current = [self exchangeTimeFrom:comStrTime];
    JJChatModelFrame *chatModelFrame = [self.chatArray lastObject];
    NSString *last = [self exchangeTimeFrom:chatModelFrame.messageModel.timestamp];
    if ([current isEqualToString:last]) {
        return YES;
    }
    return NO;
}

- (NSString*)exchangeTimeFrom:(long long)timeStamp
{
    NSDate *timeDate = [[NSDate alloc]initWithTimeIntervalSince1970:timeStamp/1000];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy年MM月dd日 HH";
    NSString *timeStr = [dateFormatter stringFromDate:timeDate];
    return timeStr;
}

//创建会话,读取历史消息

- (void)creatSession
{
    if (self.chatArray.count > 0) {
        [self.chatArray removeAllObjects];
    }
    EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:self.conversationId type:EMConversationTypeChat createIfNotExist:YES];
    long long timestamp = 0;//拿来所有聊天记录
    long long toTimeStamp = [NSDate getDateTimeTOMilliSeconds:[NSDate dateWithTimeIntervalSinceNow:0]];
    int MAX_ITEM = 1000;
    
    [conversation loadMessagesFrom:timestamp to:toTimeStamp count:MAX_ITEM completion:^(NSArray *aMessages, EMError *aError) {
        if (!aError) {
            {
                for (EMMessage *message in aMessages) {
                    EMMessageBody *msgBody = message.body;
                    switch (msgBody.type) {
                        case EMMessageBodyTypeText://目前只支持文字聊天
                        {
                            // 收到的文字消息
                            EMTextMessageBody *textBody = (EMTextMessageBody *)msgBody;
                            NSString *chatContent_text = textBody.text;
                            
                            JJMessageChatModel *messageModel  = [[JJMessageChatModel alloc]init];
                            if (message.direction == EMMessageDirectionSend) {
                                messageModel.messageDirection = MessageDirectionSend;
                            }
                            else {
                                messageModel.messageDirection = MessageDirectionReceive;
                            }
                            messageModel.avatar = @"";
                            messageModel.messageId = message.messageId;
                            messageModel.timestamp = message.timestamp;
                            messageModel.messageContent = chatContent_text;
                            messageModel.remoteImageUrl = nil;
                            messageModel.image = nil;
                            messageModel.type = [[message.ext valueForKey:@"type"] intValue];
                            if (messageModel.type == 2) {
                                messageModel.liveModel = [JJLiveModel modelWithDictionary:message.ext];
                            } else if (messageModel.type == 1){
                                messageModel.videoModel = [JJShortVideoModel modelWithDictionary:message.ext];
                            }
                           
                            BOOL isEqual = NO;
                            
                            if (self.chatArray) {
                                isEqual = [self timeIsEqualInOneHour:messageModel.timestamp];
                            }
                            
                            JJChatModelFrame *chatModelFrame = [[JJChatModelFrame alloc] initWithFrameModel:messageModel timestamp:self.lastTime];
                            chatModelFrame.type = [[message.ext valueForKey:@"type"] intValue];
                            self.lastTime = message.timestamp;
                            if (chatModelFrame.messageDirection == MessageDirectionSend) {
                                chatModelFrame.messageModel.avatar = self.messageModel.toUserHead;
                            } else {
                                chatModelFrame.messageModel.avatar = self.messageModel.uhead;
                            }
                            [self.chatArray addObject:chatModelFrame];
                        }
                            break;
                        case EMMessageBodyTypeImage:{
                            // 收到的图片消息
                            EMImageMessageBody *imageBody = (EMImageMessageBody *)msgBody;
                            JJMessageChatModel *messageModel  = [[JJMessageChatModel alloc]init];
                            if (message.direction == EMMessageDirectionSend) {
                                messageModel.messageDirection = MessageDirectionSend;
                            }
                            else {
                                messageModel.messageDirection = MessageDirectionReceive;
                            }
                            messageModel.avatar = @"";
                            messageModel.messageId = message.messageId;
                            messageModel.messageContent = nil;
                            messageModel.localImageUrl = imageBody.localPath;
                            messageModel.remoteImageUrl = imageBody.remotePath;
                            messageModel.timestamp = message.timestamp;
                            messageModel.imaageSize = imageBody.size;
                            messageModel.type = 3;
                            
                            BOOL isEqual = NO;
                            
                            if (self.chatArray) {
                                isEqual = [self timeIsEqualInOneHour:messageModel.timestamp];
                            }
                            JJChatModelFrame *chatModelFrame = [[JJChatModelFrame alloc] initWithFrameModel:messageModel timestamp:self.lastTime];
                            chatModelFrame.type = 3;
                            self.lastTime = message.timestamp;
                            if (chatModelFrame.messageDirection == MessageDirectionSend) {
                                chatModelFrame.messageModel.avatar = self.messageModel.toUserHead;
                            } else {
                                chatModelFrame.messageModel.avatar = self.messageModel.uhead;
                            }
                            [self.chatArray addObject:chatModelFrame];
                        }
                            break;
                        default:
                            break;
                    }
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                    if (self.tableView.contentSize.height > self.tableView.height) {
                        [self.tableView scrollToBottom];
                    }
                });
            }
        }
    }];

}

//文本消息的发送

- (void)sendMessageWithMessage:(NSString *)messageStr andType:(NSMutableDictionary *)param;
{
    if (messageStr.length > 0 || param.count > 0) {
        
        if (!param) {
            param = [[NSMutableDictionary alloc] init];
        }
        [param setObject:[JJConfig getOwnNicename]?:@"" forKey:@"uname"];
        [param setObject:[JJConfig myProfile].avatar?:@"" forKey:@"uhead"];
        if (messageStr && messageStr.length > 0) {
            [param setObject:@"0" forKey:@"type"];
        }
        if (_messageModel) {
            [param setObject:_messageModel.toUserHead?:@"" forKey:@"toUserHead"];
            [param setObject:_messageModel.toUserName?:@"" forKey:@"toUserName"];
        }
        
        EMTextMessageBody *messageBody = [[EMTextMessageBody alloc] initWithText:messageStr];
        EMMessage *message = [[EMMessage alloc] initWithConversationID:self.conversationId from:[JJConfig getOwnID] to:self.conversationId body:messageBody ext:param];
        message.chatType = EMChatTypeChat;
        message.direction = EMMessageDirectionSend;
        NSLog(@"%@", message.ext);
        //发送消息
        [[EMClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
            
        } completion:^(EMMessage *message, EMError *error) {
            message.chatType = EMChatTypeChat;
            EMMessageBody *msgBody = message.body;
            if (!error) {
                
                //发送的是文字消息
                EMTextMessageBody *textBody = (EMTextMessageBody *)msgBody;
                JJMessageChatModel *messageModel = [[JJMessageChatModel alloc] init];
                if (message.direction == EMMessageDirectionSend) {
                    messageModel.messageDirection = MessageDirectionSend;
                }
                else {
                    messageModel.messageDirection = MessageDirectionReceive;
                }
                messageModel.avatar = @"";
                messageModel.messageId = message.messageId;
                messageModel.messageContent = textBody.text;
                messageModel.timestamp = message.timestamp;
                messageModel.type = [[message.ext valueForKey:@"type"] intValue];
                if (messageModel.type == 2) {
                    messageModel.liveModel = [JJLiveModel modelWithDictionary:message.ext];
                } else if (messageModel.type == 1){
                    messageModel.videoModel = [JJShortVideoModel modelWithDictionary:message.ext];
                }
                
                DDLogVerbose(@"发送==%@",messageModel.messageContent);
                DDLogVerbose(@"发送给对方ID==%@",self.conversationId);
                
                BOOL isEqual = NO;
                if (self.chatArray) {
                    isEqual = [self timeIsEqualInOneHour:messageModel.timestamp];
                }
                JJChatModelFrame *chatModelFrame = [[JJChatModelFrame alloc] initWithFrameModel:messageModel timestamp:self.lastTime];
                self.lastTime = message.timestamp;
                chatModelFrame.type = [[message.ext valueForKey:@"type"] intValue];
                if (chatModelFrame.messageDirection == MessageDirectionSend) {
                    chatModelFrame.messageModel.avatar = self.messageModel.toUserHead;
                } else {
                    chatModelFrame.messageModel.avatar = self.messageModel.uhead;
                }
                [self.chatArray addObject:chatModelFrame];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                    [self.tableView scrollToRow:self.chatArray.count - 1 inSection:0 atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                });
            }
            else {
             DDLogVerbose(@"错误描述==%@",error.errorDescription);
            }
        }];
    }
}

//对象转换为字典的方法

- (NSMutableDictionary *)returnToDictionaryWithModel:(JJMessageModel *)model
{
    NSMutableDictionary *userDic = [NSMutableDictionary dictionary];
    unsigned int count = 0;
    objc_property_t *properties = class_copyPropertyList([JJMessageModel class], &count);
    for (int i = 0; i < count; i++) {
        const char *name = property_getName(properties[i]);
        
        NSString *propertyName = [NSString stringWithUTF8String:name];
        id propertyValue = [model valueForKey:propertyName];
        if (propertyValue) {
            [userDic setObject:propertyValue forKey:propertyName];
        }
    }
    free(properties);
    
    return userDic;
}

//图片消息的发送

- (void)sendImageMessage
{
    if (self.sendImage) {
        NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
        [param setObject:[JJConfig getOwnNicename]?:@"" forKey:@"uname"];
        [param setObject:[JJConfig myProfile].avatar?:@"" forKey:@"uhead"];
        [param setObject:@"3" forKey:@"type"];
        if (_messageModel) {
            [param setObject:_messageModel.toUserHead?:@"" forKey:@"toUserHead"];
            [param setObject:_messageModel.toUserName?:@"" forKey:@"toUserName"];
        }

        NSData *imageData = UIImageJPEGRepresentation(self.sendImage, 1);
        EMImageMessageBody *imageMessageBody = [[EMImageMessageBody alloc] initWithData:imageData displayName:nil];
        EMMessage *imageMessage = [[EMMessage alloc] initWithConversationID:self.conversationId from:[JJConfig getOwnID] to:self.conversationId body:imageMessageBody ext:param];
        
        imageMessage.chatType = EMChatTypeChat;
        imageMessage.direction = EMMessageDirectionSend;
        
        [[EMClient sharedClient].chatManager sendMessage:imageMessage progress:^(int progress) {
            
        } completion:^(EMMessage *message, EMError *error) {
            
            if (!error) {
                NSLog(@"发送图片消息");
                JJMessageChatModel *messageModel = [[JJMessageChatModel alloc] init];
                if (message.direction == EMMessageDirectionSend) {
                    messageModel.messageDirection = MessageDirectionSend;
                }
                else {
                    messageModel.messageDirection = MessageDirectionReceive;
                }
                messageModel.avatar = @"";
                messageModel.messageId = message.messageId;
                messageModel.timestamp = message.timestamp;
                messageModel.type = 3;
                messageModel.imaageSize = self.sendImage.size;
                messageModel.image = self.sendImage;
                DDLogVerbose(@"发送==%@",messageModel.messageContent);
                DDLogVerbose(@"发送给对方ID==%@",self.conversationId);
                
                BOOL isEqual = NO;
                if (self.chatArray) {
                    isEqual = [self timeIsEqualInOneHour:messageModel.timestamp];
                }
                JJChatModelFrame *chatModelFrame = [[JJChatModelFrame alloc] initWithFrameModel:messageModel timestamp:self.lastTime];
                chatModelFrame.type = 3;
                self.lastTime = message.timestamp;
                if (chatModelFrame.messageDirection == MessageDirectionSend) {
                    chatModelFrame.messageModel.avatar = self.messageModel.toUserHead;
                } else {
                    chatModelFrame.messageModel.avatar = self.messageModel.uhead;
                }
                [self.chatArray addObject:chatModelFrame];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                    [self.tableView scrollToRow:self.chatArray.count - 1 inSection:0 atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                    
                });
            } 
        }];
    }
}

//加载接收的消息

- (void)loadReceivedMessageWithArray:(NSArray *)messageArr
{
    if (messageArr.count > 0) {
        for (EMMessage *message in messageArr) {
            if (![message.conversationId isEqualToString:_conversationId]) {
                return;
            }
            EMMessageBody *msgBody = message.body;
            self.messageModel.toUserHead = [message.ext objectForKey:@"toUserHead"];
            self.messageModel.toUserName = [message.ext objectForKey:@"toUserName"];
            self.messageModel.uhead = [message.ext objectForKey:@"uhead"];
            self.messageModel.uname = [message.ext objectForKey:@"uname"];
            switch (msgBody.type) {
                    
                 //文字
                case EMMessageBodyTypeText:
                {
                    // 收到的文字消息
                    EMTextMessageBody *textBody = (EMTextMessageBody *)msgBody;
                    NSString *chatDetailtext = textBody.text;
                    JJMessageChatModel *messageModel  = [[JJMessageChatModel alloc] init];
                    if (message.direction == EMMessageDirectionSend) {
                        messageModel.messageDirection = MessageDirectionSend;
                    }
                    else {
                        messageModel.messageDirection = MessageDirectionReceive;
                    }
                    messageModel.avatar = @"";
                    messageModel.messageId = message.messageId;
                    messageModel.messageContent = chatDetailtext;
                    messageModel.timestamp = message.timestamp;
                    messageModel.type = [[message.ext valueForKey:@"type"] intValue];
                    messageModel.image = nil;
                    messageModel.remoteImageUrl = nil;
                    messageModel.localImageUrl = nil;
                    if (messageModel.type == 2) {
                        messageModel.liveModel = [JJLiveModel modelWithDictionary:message.ext];
                    } else if (messageModel.type == 1){
                        messageModel.videoModel = [JJShortVideoModel modelWithDictionary:message.ext];
                    }
                    BOOL isEqual = NO;
                    
                    if (self.chatArray) {
                        isEqual = [self timeIsEqualInOneHour:messageModel.timestamp];
                    }
                    JJChatModelFrame *chatModelFrame = [[JJChatModelFrame alloc] initWithFrameModel:messageModel timestamp:self.lastTime];
                    chatModelFrame.type = [[message.ext valueForKey:@"type"] intValue];
                    self.lastTime = message.timestamp;
                    if (chatModelFrame.messageDirection == MessageDirectionSend) {
                        chatModelFrame.messageModel.avatar = self.messageModel.toUserHead;
                    } else {
                        chatModelFrame.messageModel.avatar = self.messageModel.uhead;
                    }
                    [self.chatArray addObject:chatModelFrame];
                    
                    [self.tableView reloadData];
                    [self.tableView scrollToRow:self.chatArray.count - 1 inSection:0 atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                    
                }
                    
                    break;
                    
                //图片
                case EMMessageBodyTypeImage:
                {
                    [self performSelector:@selector(loadImageMessage:) withObject:message afterDelay:2.0f];
//                    [self loadImageMessage:message];
                }
                break;
                default:
                    break;
            }
        }
    }
}

- (void) loadImageMessage:(EMMessage *)message {
    EMMessageBody *msgBody = message.body;
    EMImageMessageBody *imageBody = (EMImageMessageBody *)msgBody;
    
    JJMessageChatModel *messageModel  = [[JJMessageChatModel alloc] init];
    if (message.direction == EMMessageDirectionSend) {
        messageModel.messageDirection = MessageDirectionSend;
    }
    else {
        messageModel.messageDirection = MessageDirectionReceive;
    }
    messageModel.avatar = @"";
    messageModel.messageId = message.messageId;
    messageModel.timestamp = message.timestamp;
    messageModel.localImageUrl = imageBody.localPath;
    messageModel.remoteImageUrl = imageBody.remotePath;
    messageModel.imaageSize = imageBody.size;
    messageModel.messageContent = nil;
    messageModel.type = 3;
    BOOL isEqual = NO;
    
    if (self.chatArray) {
        isEqual = [self timeIsEqualInOneHour:messageModel.timestamp];
    }
    JJChatModelFrame *chatModelFrame = [[JJChatModelFrame alloc] initWithFrameModel:messageModel timestamp:self.lastTime];
    chatModelFrame.type = 3;
    self.lastTime = message.timestamp;
    if (chatModelFrame.messageDirection == MessageDirectionSend) {
        chatModelFrame.messageModel.avatar = self.messageModel.toUserHead;
    } else {
        chatModelFrame.messageModel.avatar = self.messageModel.uhead;
    }
    [self.chatArray addObject:chatModelFrame];
    
    [self.tableView reloadData];
    [self.tableView scrollToRow:self.chatArray.count - 1 inSection:0 atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

- (void)loadMoreView
{
    [UIView animateWithDuration:0.25 animations:^{
        //背景View
        JJUIView *backView = [[JJUIView alloc] initWithFrame:CGRectMake(0.0, kJJCommonScreenHeight - 432.0/2, kJJCommonScreenWidth, 432.0/2)];
        self.tableView.frame = CGRectMake(0, 0, kJJCommonScreenWidth, kJJCommonScreenHeight - 50 - 432.0/2);
        backView.backgroundColor = [UIColor lightTextColor];
        self.backView = backView;
        [self.view addSubview:backView];
        
        //图片图片
        JJUIButton *pictureButton = [JJUIButton buttonWithType:UIButtonTypeCustom];
        [pictureButton setImage:[UIImage imageNamed:@"chat_image"] forState:UIControlStateNormal];
        [pictureButton addTarget:self action:@selector(pictureButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.backView addSubview:pictureButton];
        
        [pictureButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.backView).offset(44/2);
            make.top.equalTo(self.backView).offset(39.0f/2);
            make.width.height.equalTo(@50);
        }];
        
        //图片文字
        JJUILabel *pictureLabel = [[JJUILabel alloc] init];
        pictureLabel.text = @"图片";
        pictureLabel.textColor = [UIColor colorWithHexString:@"999999"];
        pictureLabel.font = [UIFont fontWithName:kPingFangSC_Regular size:24/2];
        [self.backView addSubview:pictureLabel];
        
        [pictureLabel sizeToFit];
        [pictureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(pictureButton.mas_bottom).offset(10.0);
            make.centerX.equalTo(pictureButton);
        }];
        
        //收藏图片
        JJUIButton *storeButton = [JJUIButton buttonWithType:UIButtonTypeCustom];
        [storeButton setImage:[UIImage imageNamed:@"chat_collection"] forState:UIControlStateNormal];
        [storeButton addTarget:self action:@selector(storeButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.backView addSubview:storeButton];
        
        [storeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(pictureButton.mas_right).offset(88/2);
            make.top.equalTo(pictureButton);
            make.width.height.equalTo(@50);
        }];
        
        //收藏文字
        JJUILabel *storeLabel = [[JJUILabel alloc] init];
        storeLabel.text = @"收藏";
        storeLabel.textColor = [UIColor colorWithHexString:@"999999"];
        storeLabel.font = [UIFont fontWithName:kPingFangSC_Regular size:24/2];
        [self.backView addSubview:storeLabel];
        
        [storeLabel sizeToFit];
        [storeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(pictureLabel);
            make.centerX.equalTo(storeButton);
        }];
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - Action && Notification

- (void)didReceivedMessages:(NSNotification *)noti
{
    NSArray *messageArr = (NSArray *)noti.object;
    [self loadReceivedMessageWithArray:messageArr];
}

- (void)storeButtonDidClick:(JJUIButton *)storeButton
{
    NSLog(@"收藏按钮被点击了");
    JJPersonCenterContainVC *nextVC = [[JJPersonCenterContainVC alloc] init];
    nextVC.isChat = YES;
    nextVC.delegate = self;
    [self.navigationController pushViewController:nextVC animated:YES];
}

- (void)pictureButtonDidClick:(JJUIButton *)pictureButton
{
    NSLog(@"图片按钮被点击了");
    
    UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
    imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerVC.allowsEditing = YES;
    imagePickerVC.delegate = self;
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

- (void)moreButtonDidClick:(JJUIButton *)moreButton
{
    [self.textField resignFirstResponder];
    
    if (self.backView) {
        [self.backView removeFromSuperview];
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        //按钮上移
        self.tableView.frame = CGRectMake(0, 0, kJJCommonScreenWidth, kJJCommonScreenHeight - 50 - 432/2);
        self.sendView.frame = CGRectMake(0, kJJCommonScreenHeight - 50 - 432/2, kJJCommonScreenWidth, 50);
        if (self.tableView.contentSize.height > self.tableView.height) {
            [self.tableView scrollToBottom];
        }
    } completion:^(BOOL finished) {
        
    }];
    
    [self loadMoreView];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.chatArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JJMessageChatCell *cell = [tableView dequeueReusableCellWithIdentifier:JJMessageChatCellID forIndexPath:indexPath];
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.chatModelFrame = self.chatArray[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JJChatModelFrame *chatModelFrame = self.chatArray[indexPath.row];
    return chatModelFrame.cellHeight;
}

- (void)didClickImagePlusImage:(UIImage *)image{
    if (image) {
        UIButton *btn = [[UIButton alloc] initWithFrame:self.view.frame];
        [btn setBackgroundColor:[UIColor blackColor]];
        [btn setImage:image forState:UIControlStateNormal];
        btn.alpha = 0;
        [btn addTarget:self action:@selector(didClickHiddenImageView:) forControlEvents:UIControlEventTouchUpInside];
        [[UIApplication sharedApplication].keyWindow addSubview:btn];
        [UIView animateWithDuration:0.25 animations:^{
            btn.alpha = 1;
        }];
    }
}

- (void) didClickHiddenImageView:(UIButton *)sender {
    [UIView animateWithDuration:0.25 animations:^{
        sender.alpha = 0;
    } completion:^(BOOL finished) {
        [sender removeFromSuperview];
    }];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self endEdit];
    return YES;
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    self.sendImage = info[UIImagePickerControllerOriginalImage];
    
    //发送图片消息
    [self sendImageMessage];
}

@end

这里还有几个类需要说明一下。
首先要说的是JJMessageChatModel这个类,这个类的作用就是存放聊天室每个cell里面的数据模型。

#import <Foundation/Foundation.h>
#import "JJLiveModel.h"
#import "JJShortVideoModel.h"

typedef NS_ENUM(NSInteger ,MessageDirection)
{
    MessageDirectionSend = 1,    //发送消息
    MessageDirectionReceive      //接受消息
    
};

//聊天模型

@interface JJMessageChatModel : JJBaseModel

@property (nonatomic, copy) NSString *avatar;                       //头像
@property (nonatomic, assign) MessageDirection messageDirection;    //消息来源类型
@property (nonatomic, copy) NSString *messageId;                    //消息id;
@property (nonatomic, copy) NSString *messageContent;               //文本消息;
@property (nonatomic, assign) long long timestamp;                  //消息时间戳
@property (nonatomic, copy) NSString *verify_info;                  //认证信息
@property (nonatomic, copy) NSString *cornerMark;                   //头像角标
@property (nonatomic, copy) NSString *message;                      //消息
@property (nonatomic, copy) NSString *remoteImageUrl;               //图片网络地址
@property (nonatomic, copy) NSString *localImageUrl;                //图片沙盒地址
@property (nonatomic, copy) UIImage *image;                         //图片
@property (nonatomic, assign) CGSize imaageSize;
@property (nonatomic, strong) JJShortVideoModel *videoModel;
@property (nonatomic, strong) JJLiveModel *liveModel;
@property (nonatomic, assign) int type;

@end

下面还有个类就是JJChatModelFrame,这个类的作用就是负责给每一个cell赋值并调整每一个cell的大小,如下所示:

1. JJChatModelFrame.h
#import <Foundation/Foundation.h>
#import "JJMessageViewController.h"
#import "JJMessageChatModel.h"

#define ChatHeadImage_height  42.0f
#define TimeLabel_height  20.0f

@interface JJChatModelFrame : NSObject

/** 时间的Frame */
@property (nonatomic,assign)CGRect timeLabelFrame;

/** 头像的Frame */
@property (nonatomic,assign)CGRect headImageFrame;

/** 聊天内容的Frame */
@property (nonatomic,assign)CGRect contentFrame;

/** 认证标志的Frame */
@property (nonatomic,assign)CGRect verifyBadgeFrame;

/** 消息来源类型 */
@property (nonatomic,assign) MessageDirection messageDirection;

/** 模型数据 */
@property (nonatomic,strong) JJMessageChatModel *messageModel;

/*cell的高度 */
@property (nonatomic,assign)CGFloat cellHeight;

@property (nonatomic, assign) int type;                             //1. 文字,2. 节目   3. 创意视频 4. 图片

/** 通过模型数据计算出对应的Frame,并且返回出modelFrame自己这个对象 */
- (instancetype)initWithFrameModel:model timestamp:(NSTimeInterval)timestamp;

//和上面同理
+ (instancetype)modelFrame:(JJMessageChatModel *)messageModel timestamp:(NSTimeInterval)timestamp;

@end

2. JJChatModelFrame.m
#import "JJChatModelFrame.h"

#define contentFont [UIFont systemFontOfSize:15.0]//聊天消息字体的大小
#define distance 8 //边距

@implementation JJChatModelFrame

#pragma mark - Object Public Function

- (instancetype)initWithFrameModel:(JJMessageChatModel *)messageModel timestamp:(NSTimeInterval)timestamp
{
    self = [super init];
    if (self) {
        _messageModel = messageModel;
        NSString *timeStr = [self exchangeTimeFrom:messageModel.timestamp];
        NSString *lastStr = [self exchangeTimeFrom:timestamp];
        BOOL timeBool = [timeStr isEqualToString:lastStr];
        CGSize timeSize=[timeStr sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12.0f]}]; //通过时间NSString计算出宽度
        if(!timeBool){//前后时间不相等 不相等显示,相等不显示
            self.timeLabelFrame=CGRectMake(kJJCommonScreenWidth/2.0-(timeSize.width+20)/2.0, 2, timeSize.width+20, TimeLabel_height);//显示时间的Frame
        }
        else{
            self.timeLabelFrame=CGRectZero;
        }
        float width, height;
        if (_messageModel.type == 0) {
            CGRect btnRect=[_messageModel.messageContent boundingRectWithSize:CGSizeMake(kJJCommonScreenWidth*0.6, MAXFLOAT)
                                                                      options:NSStringDrawingUsesLineFragmentOrigin
                                                                   attributes:@{NSFontAttributeName:contentFont}
                                                                      context:nil];
            width = btnRect.size.width+20*2;
            height = btnRect.size.height+10*2;
        } else if (_messageModel.type == 1) {
            width = 150;
            height = _messageModel.videoModel.picHeight*150/_messageModel.videoModel.picWidth;
            _messageModel.messageContent = @"这是一个短视频";
        } else if (_messageModel.type == 2) {
            width = 389.0f/2;
            height = 320/2;
            _messageModel.messageContent = @"这是一个节目";
        } else {
            width = 150;
            height = _messageModel.imaageSize.height*150/_messageModel.imaageSize.width;
        }
        if (_messageModel.messageDirection == MessageDirectionSend) {
            self.headImageFrame = CGRectMake(kJJCommonScreenWidth-distance-ChatHeadImage_height, CGRectGetMaxY(self.timeLabelFrame)+distance, ChatHeadImage_height, ChatHeadImage_height);
            self.contentFrame = CGRectMake(kJJCommonScreenWidth-distance-ChatHeadImage_height-distance-width, CGRectGetMaxY(self.timeLabelFrame)+15, width, height);
            
        }else if (_messageModel.messageDirection == MessageDirectionReceive){
            self.headImageFrame=CGRectMake(distance, CGRectGetMaxY(self.timeLabelFrame)+distance,ChatHeadImage_height, ChatHeadImage_height);
            self.contentFrame=CGRectMake(distance+ChatHeadImage_height+distance, CGRectGetMaxY(self.timeLabelFrame)+15, width, height);
        }
        _messageDirection = messageModel.messageDirection;
        
        if (messageModel.verify_info == nil) {
            _verifyBadgeFrame = CGRectZero;
        }else if (messageModel.verify_info && messageModel.verify_info.length!=0){
            _verifyBadgeFrame =  CGRectMake(CGRectGetMaxX(self.headImageFrame)-13, CGRectGetMaxY(self.headImageFrame)-13, 13, 13);
        }
        
        CGFloat  cellH=MAX(CGRectGetMaxY(self.contentFrame), CGRectGetMaxY(self.headImageFrame));//比较输入的内容和头像的Y值哪个大
        if (cellH == NAN) {
            return 0;
        }
        self.cellHeight=cellH+distance;//返回Cell的高度
    }
    return self;
}

#pragma mark - Class Public Function

+ (instancetype)modelFrame:(JJMessageChatModel *)messageModel timestamp:(NSTimeInterval)timestamp{
    return [[self alloc]initWithFrameModel:messageModel timestamp:timestamp];
}

#pragma mark - Object Private Function

- (NSString*)exchangeTimeFrom:(long long)timeStamp
{
    NSDate *timeDate = [[NSDate alloc]initWithTimeIntervalSince1970:timeStamp/1000];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy年MM月dd日 HH:mm";
    NSString *timeStr = [dateFormatter stringFromDate:timeDate];
    return timeStr;
}

@end

还有一个界面需要说的就是,我们聊天室前一个界面,那就是消息列表页,这个页面主要就是记录系统消息,以及其他都谁给发过了消息,方便用户点击进入聊天室进行聊天。下面直接给出代码了。

//聊天消息列表页
1. JJMessageViewController.m
#import "JJMessageViewController.h"
#import "JJFabulousVC.h"
#import "JJChatViewController.h"
#import "JJMessageCommentVC.h"
#import "JJMessageCell.h"
#import "JJMessageModel.h"
#import "JJMessageDataTool.h"

//消息界面
@interface JJMessageViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <JJMessageModel *>*messageArray;
@property (nonatomic, copy) NSString *conversationId;
@property (nonatomic,strong) NSMutableArray *conversationIdArrM;
@property (nonatomic, strong) NSMutableArray *sessionArray;

@end

@implementation JJMessageViewController

static NSString *JJMessgaeCellID = @"JJMessgaeCellID";

#pragma mark - Override Base Function

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *array = @[@{@"uname":@"评论我的", @"imgPath":@"personCenter_comment"},
                       @{@"uname":@"赞我的", @"imgPath":@"personCenter_admire"},
                       @{@"uname":@"客服", @"imgPath":@"personCenter_kefu"},
                       ];
    if (![[JJMessageDataTool shareMessageTool] getLoginStatus]) {
        [[JJMessageDataTool shareMessageTool] loginEMClient];
    }
    self.messageArray = [NSMutableArray array];
    self.conversationIdArrM = [NSMutableArray array];
    
    for (NSDictionary *dic in array) {
        JJMessageModel *model = [JJMessageModel modelWithDictionary:dic];
        [self.messageArray addObject:model];
    }
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[JJMessageCell class] forCellReuseIdentifier:JJMessgaeCellID];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self getAllSessions];
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Object Private Function

- (void)loadMessageDataWithArr:(NSArray *)messageArr
{
    if (messageArr.count > 0) {
        
        for (EMMessage *message in messageArr) {
            
            JJMessageModel *model = [[JJMessageModel alloc] init];
            model.uname = [JJConfig getOwnNicename];
            
            self.conversationId = message.conversationId;
            [self.messageArray addObject:model];
        }
        [self.tableView reloadData];
    }
}

#pragma mark - Action && Notification

- (void)didReceivedMessages:(NSNotification *)noti
{
    NSDictionary *messageDict = noti.userInfo;    
    NSArray *messageArr = [messageDict objectForKey:@"receivedMessage"];
    
    if (messageArr.count > 0) {
        
        for (EMMessage *message in messageArr) {
            
            JJMessageModel *model = [[JJMessageModel alloc] init];
            self.conversationId = message.conversationId;
            [self.conversationIdArrM addObject:self.conversationId];
            [self.messageArray addObject:model];
        }
        [self.tableView reloadData];
    }
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.messageArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JJMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:JJMessgaeCellID forIndexPath:indexPath];
    cell.indexPath = indexPath;
    cell.model = self.messageArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            NSLog(@"跳转评论页");
            JJMessageCommentVC *commentVC = [[JJMessageCommentVC alloc] init];
            [self.navigationController pushViewController:commentVC animated:YES];
        }
            break;
            
        case 1:
        {
            NSLog(@"跳转赞我的页");
            JJFabulousVC *nextVC = [[JJFabulousVC alloc] init];
            nextVC.title = @"赞";
            [self.navigationController pushViewController:nextVC animated:YES];
        }
            break;
            
        case 2:
        {
            NSLog(@"跳转客服页");
        }
            break;
            
        default:
        {
            NSLog(@"跳转聊天页");
            JJChatViewController *nextVC = [[JJChatViewController alloc] init];
            nextVC.messageModel = self.messageArray[indexPath.row];
            nextVC.conversationId = self.messageArray[indexPath.row].conversationId;
            nextVC.title = [nextVC.messageModel.uname isEqualToString:[JJConfig getOwnNicename]]?nextVC.messageModel.toUserName:nextVC.messageModel.uname;
            [self.navigationController pushViewController:nextVC animated:YES];
        }
        break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

-(void)getAllSessions
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
        _sessionArray = (NSMutableArray*)conversations;
        dispatch_async(dispatch_get_main_queue(), ^{
            if(_sessionArray.count){
                for (EMConversation *conversation in _sessionArray) {
//                    [[EMClient sharedClient].chatManager deleteConversation:conversation.conversationId isDeleteMessages:YES completion:nil];
                    JJMessageModel *messageModel = [JJMessageModel modelWithDictionary:conversation.latestMessage.ext];
                    messageModel.conversationId = conversation.conversationId;
                    if (conversation.latestMessage.body.type == EMMessageBodyTypeText) {
                        EMTextMessageBody *textBody = (EMTextMessageBody *)conversation.latestMessage.body;
                        NSNumber *type = [conversation.latestMessage.ext valueForKey:@"type"];
                        if (type.integerValue == 0) {
                            messageModel.lastMessage = textBody.text;
                        } else if (type.integerValue == 2) {
                            messageModel.lastMessage = @"[收到一个节目]";
                        } else if (type.integerValue == 1) {
                            messageModel.lastMessage = @"[收到一个短视频]";
                        }
                    } else {
                        messageModel.lastMessage = @"[收到一张图片]";
                    }
                    [self.messageArray addObject:messageModel];
                }
            }
            [self.tableView reloadData];
        });
    });
}

@end

后记

未完,待续~~~

以后这就是我的

推荐阅读更多精彩内容

  • 版本记录 前言 很多app种都集成环信做第三方信息通讯工具,这里我们就看一下环信的主要功能和集成方法。先给出环信3...
    刀客传奇阅读 325评论 3 2
  • 点击查看原文 Web SDK 开发手册 SDK 概述 网易云信 SDK 为 Web 应用提供一个完善的 IM 系统...
    layjoy阅读 6,955评论 0 14
  • 1)项目里面不需要环信SDK的太多功能,只是想要聊天和好友功能,其他都不用,那SDK一定要总是跟着更新么? a.环...
    DefaultYuan阅读 23,001评论 19 59
  • 唯一能选的时间是判断低估,高估。然后就随便买,或随便卖
    新兴市场的小逻辑阅读 14评论 0 0
  • 打霜了,工地也放假了,给人装修的新房也完工了。 今天咱从米仓山深处,翻两座大山口回镇巴县城。 镇巴古称定远,又叫班...
    歪才大白话阅读 150评论 2 11