PrivateViewController.m 8.26 KB
//
//  PrivateViewController.m
//  CNLiveChatSDKDemo
//
//  Created by cnliveJunBo on 17/3/8.
//  Copyright © 2017年 cnlive. All rights reserved.
//

#import "PrivateViewController.h"

static NSString *priCellId = @"priCellId";

@interface PrivateViewController ()<UITextFieldDelegate, CNLiveChatManagerDelegate, UITableViewDelegate, UITableViewDataSource> {
    
    NSMutableArray *_messageArrayM;
    NSString *_messageSelf;
}

@property (nonatomic, strong) UITextField *textField;

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation PrivateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"单聊";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [CNLiveChatManager sharedCNLiveChatManager].delegate = self;
    
    [self.view addSubview:self.tableView];
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    gestureRecognizer.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:gestureRecognizer];
    [self.view addSubview:self.textField];
    
    _messageArrayM = [[NSMutableArray alloc] init];
    
    // 获取最新消息
    [self getPrivateChattingRecords];
    
    // 获取昵称信息
    NSString *name = [CNLiveChatManager sharedCNLiveChatManager].currentUserInfo.name;
    NSLog(@"昵称:%@",name);
}

#pragma mark - 懒加载  !!!!!!!!!!!!!!!!!!!!!!!!!!
- (UITextField *)textField {
    
    if (!_textField) {
        _textField = [self createTextFieldWithFrame:CGRectMake(10, 74, KScreenWidth - 20, 40) font:20];
        _textField.delegate = self;
    }
    return _textField;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 124, KScreenWidth, KScreenHeight - 425) style:UITableViewStylePlain];
        _tableView.rowHeight = 30;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:priCellId];
    }
    return _tableView;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource   !!!!!!!!!!!!!!!!!!!!!!!!!!

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:priCellId forIndexPath:indexPath];
    
    MessageModel *model = _messageArrayM[indexPath.row];
    
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@: %@",model.name,model.message]];
    
    if ([model.userId isEqualToString:[CNLiveChatManager sharedCNLiveChatManager].currentUserInfo.userId]) {
        
        [AttributedStr addAttribute:NSForegroundColorAttributeName
         
                              value:[UIColor redColor]
         
                              range:NSMakeRange(0, model.name.length)];
        
        cell.textLabel.attributedText = AttributedStr;
    } else {
        
        [AttributedStr addAttribute:NSForegroundColorAttributeName
         
                              value:[UIColor blackColor]
         
                              range:NSMakeRange(0, model.name.length)];
        
        cell.textLabel.attributedText = AttributedStr;
    }
    
    return cell;
}


#pragma mark - UITextFieldDelegate   !!!!!!!!!!!!!!!!!!!!!!!!!!
- (BOOL)textFieldShouldReturn:(UITextField *)textField { // 发送消息
    
    [[CNLiveChatManager sharedCNLiveChatManager] sendMessage:textField.text type:CNLive_ConversationType_PRIVATE targetId:@"20170311" success:^(CNLiveChatMessage *message) {
        
        NSLog(@"发送消息成功:%@",message.messageId);
        // 自己发送的消息不会被onReceived:方法实时监听,需要自己做处理
        MessageModel *model = [[MessageModel alloc] init];
        
        model.message = _messageSelf;
        CNLiveChatUserInfo *userInfo = [CNLiveChatManager sharedCNLiveChatManager].currentUserInfo;
        model.userId = userInfo.userId;
        model.name = userInfo.name;
        model.portraitUri = userInfo.portraitUri;
        model.type = CNLive_ConversationType_CHATROOM;
        model.messageId = message.messageId;
        
        [_messageArrayM addObject:model];
        
        // 此处更新 UI 应到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            
            [self scrollToBottom];
        });
        
    } error:^(CNLiveChatErrorCode errors, NSString *messageId, NSString *targetId) {
        
        NSLog(@"向:%@发送消息失败,错误代码:%ld,信息ID:%@",targetId,(long)errors,messageId);
    }];
    
    _messageSelf = textField.text;
    textField.text = @"";
    
    return YES;
}


#pragma mark - CNLiveChatManagerDelegate    !!!!!!!!!!!!!!!!!!!!!!!!!!
- (void)onReceived:(CNLiveChatMessage *)message {
    
    NSLog(@"收到消息类型:%lu,消息ID:%@,消息内容:%@,消息发送者信息:%@",(unsigned long)message.conversationType,message.targetId,message.messageContent,message.userInfo);
    
    if (message.conversationType == CNLive_ConversationType_PRIVATE) {
        
        MessageModel *model = [[MessageModel alloc] init];
        
        model.message = message.messageContent;
        model.userId = message.userInfo.userId;
        model.name = message.userInfo.name;
        model.portraitUri = message.userInfo.portraitUri;
        model.type = message.conversationType;
        
        [_messageArrayM addObject:model];
        
        [self.tableView reloadData];
        
        [self scrollToBottom];
    }
}

- (void)onConnectionStatusChanged:(CNLiveConnectionStatus)status {
    
    NSLog(@"当前连接状态:%ld",(long)status);
}

- (void)kickedByAnotherDevice {
    
    NSString *userId = [CNLiveChatManager sharedCNLiveChatManager].currentUserInfo.userId;
    NSLog(@"账号%@在其他设备登陆",userId);
}


#pragma mark - 创建文本框   !!!!!!!!!!!!!!!!!!!!!!!!!!
- (UITextField *)createTextFieldWithFrame:(CGRect)frame font:(float)font {
    
    UITextField *textField = [[UITextField alloc] init];
    [textField setFrame:frame];
    textField.returnKeyType = UIReturnKeySend;
    textField.layer.borderWidth = 1.0f;
    textField.layer.cornerRadius = frame.size.height * 0.1;
    [textField setFont:[UIFont systemFontOfSize:font]];
    textField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 6, 0)];
    textField.leftViewMode = UITextFieldViewModeAlways;
    return textField;
}

#pragma mark - 获取私聊最新历史聊天记录   !!!!!!!!!!!!!!!!!!!!!!!!
- (void)getPrivateChattingRecords {
    
    // 获取最新消息
    NSArray *messageArray = [[CNLiveChatManager sharedCNLiveChatManager] getLatestMessages:CNLive_ConversationType_PRIVATE targetId:@"20170311" count:10];
    
    for (CNLiveChatMessage *message in messageArray) {
        
        MessageModel *model = [[MessageModel alloc] init];
        
        model.message = message.messageContent;
        model.userId = message.userInfo.userId;
        model.name = message.userInfo.name;
        model.portraitUri = message.userInfo.portraitUri;
        model.type = message.conversationType;
        
        if (![_messageArrayM containsObject:model]) {
            
            [_messageArrayM insertObject:model atIndex:0];
        }
        
        [self.tableView reloadData];
        
        [self scrollToBottom];
    }
}

#pragma mark - tableView 滚到最后一行   !!!!!!!!!!!!!!!!!!!!!!!!!!
- (void)scrollToBottom {
    
    if (_messageArrayM.count > 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(_messageArrayM.count - 1) inSection:0];
        
        [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

#pragma mark - 隐藏键盘  !!!!!!!!!!!!!!!!!!!!!!!
- (void)hideKeyboard {
    
    [self.textField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end