04环信聊天界面 - 发送图片消息和显示图片

1.在聊天控制器连线

/**
 *  点击上传图片
 */
- (IBAction)showImgPickerAction:(UIButton *)sender
{
    // 图片选择控制器
    UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
    imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imgPicker.delegate = self;
    [self presentViewController:imgPicker animated:YES completion:nil];
}
2.遵守协议

UIImagePickerControllerDelegate,UINavigationControllerDelegate

实现代理方法:

#pragma mark - UIImagePickerControllerDelegate
/**
 *  用户选中图片的回调
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    // 获取选中的图片
    UIImage *selectedImg = info[UIImagePickerControllerOriginalImage];
    
    // 发送图片消息
    [self sendImage:selectedImg];
    
    // 退出当前图片选择的控制器
    [self dismissViewControllerAnimated:YES completion:nil];
}
 具体发送图片的方法:
/**
 *  发送图片消息
 */
- (void)sendImage:(UIImage *)selectedImage
{
    // 构造图片消息体
    EMChatImage *orginalChatImg = [[EMChatImage alloc] initWithUIImage:selectedImage displayName:@"[图片]"];
    EMImageMessageBody *imgBody = [[EMImageMessageBody alloc]initWithImage:orginalChatImg thumbnailImage:nil];
    
    // 构造图片消息对象
    EMMessage *msg = [[EMMessage alloc] initWithReceiver:self.buddy.username bodies:@[imgBody]];
    msg.messageType = eMessageTypeChat;
    
    // 发送
    [[EaseMob sharedInstance].chatManager asyncSendMessage:msg progress:nil prepare:^(EMMessage *message, EMError *error) {
        // 准备发送图片
    } onQueue:nil completion:^(EMMessage *message, EMError *error) {
        // 发送图片成功
    } onQueue:nil];
    
    // 4.把消息添加到数据源,然后刷新表格
    [self.dataSources addObject:msg];
    [self.tableView reloadData];
    
    // 5.滚动tableView
    [self scrollToBottom];
}
自此,图片的发送完成。
二.代码优化

发送图片,发送文本,发送语音,这都有大量重复代码,我们稍加优化

#pragma mark - 发送消息(文本、语音、图片)
/**
 *  发送消息
 *
 *  @param body 消息体
 */
- (void)sendMessage:(id<IEMMessageBody>)body
{
    // 1.构造消息对象
    EMMessage *msg = [[EMMessage alloc] initWithReceiver:self.buddy.username bodies:@[body]];
    msg.messageType = eMessageTypeChat;
    
    // 2.发送消息
    [[EaseMob sharedInstance].chatManager asyncSendMessage:msg progress:nil prepare:^(EMMessage *message, EMError *error) {
        // 准备发送
    } onQueue:nil completion:^(EMMessage *message, EMError *error) {
        // 发送成功
    } onQueue:nil];
    
    // 4.把消息添加到数据源
    [self.dataSources addObject:msg];
    
    // 5.刷新表格
    [self.tableView reloadData];
    
    // 6.滚动tableView
    [self scrollToBottom];

}

/**
 *  发送文本消息
 */
- (void)sendText:(NSString *)text
{
    // 0.处理字符串中的换行符
    text = [text substringToIndex:text.length -1];
    
    // 1.准备创建消息实例需要的参数
    EMChatText *chatText = [[EMChatText alloc] initWithText:text];
    EMTextMessageBody *textBody = [[EMTextMessageBody alloc] initWithChatObject:chatText];
    
    // 2.发送
    [self sendMessage:textBody];
}

/**
 *  发送语音消息
 *
 *  @param recordPath 语音文件路径
 *  @param duration   时间
 */
- (void)sendVoice:(NSString *)recordPath duration:(NSInteger)duration
{
    // 1.构造一个 语音消息体
    EMChatVoice *chatVoice = [[EMChatVoice alloc] initWithFile:recordPath displayName:@"[语音]"];
    EMVoiceMessageBody *voiceBody = [[EMVoiceMessageBody alloc] initWithChatObject:chatVoice];
    voiceBody.duration = duration;
    
    // 2.发送
    [self sendMessage:voiceBody];
}

/**
 *  发送图片消息
 */
- (void)sendImage:(UIImage *)selectedImage
{
    // 1.构造图片消息体
    EMChatImage *orginalChatImg = [[EMChatImage alloc] initWithUIImage:selectedImage displayName:@"[图片]"];
    EMImageMessageBody *imgBody = [[EMImageMessageBody alloc]initWithImage:orginalChatImg thumbnailImage:nil];
    
    // 2.发送
    [self sendMessage:imgBody];
}

三.把图片显示到cell上
//
//  ChatCell.m
//  环信项目
//
//  Created by yongkaidong on 16/2/14.
//  Copyright © 2016年 com.yongkaidong. All rights reserved.
//

#import "ChatCell.h"
#import "EaseMob.h"
#import "AudioPlayTool.h"
#import "UIImageView+WebCache.h"

@interface ChatCell()
/**
 *  聊天的图片控件(因为懒加载创建所用strong)
 */
@property(nonatomic,strong)UIImageView *chatImageView;
@end

@implementation ChatCell

- (UIImageView *)chatImageView
{
    if (!_chatImageView) {
        _chatImageView = [[UIImageView alloc] init];
    }
    return _chatImageView;
}


/**
 *  初始化
 */
-(void)awakeFromNib
{
    // 1.给messageLabel添加手势
    self.messageLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(messageLabelTap:)];
    [self.messageLabel addGestureRecognizer: tap];
}

/**
 *  当用户点击messageLabel播放语言
 */
- (void)messageLabelTap:(UIGestureRecognizer *)recognizer
{
    id body = self.message.messageBodies[0];
    if ([body isKindOfClass:[EMVoiceMessageBody class]]) {
        // 播放语音
        BOOL receiver = [self.reuseIdentifier isEqualToString:recivierCell];
        [AudioPlayTool playWithMessage:self.message messageLabel:self.messageLabel receiver:receiver];
    }
}

- (CGFloat)cellHeight
{
    // 1.重新布局子控件(后label的高度已经确定了)
    [self layoutIfNeeded];
    
    // 2.返回cell的高度
    return self.messageLabel.frame.size.height + 50;
}

- (void)setMessage:(EMMessage *)message
{
    _message = message;
    
    // 0.重用cell要移除聊天图片控件
    [self.chatImageView removeFromSuperview];
    
    // 1.获取消息体
    id body = message.messageBodies[0];
    if ([body isKindOfClass:[EMTextMessageBody class]]) { //文本消息
        EMTextMessageBody *textBody = body;
        self.messageLabel.text = textBody.text;
    }else if ([body isKindOfClass:[EMVoiceMessageBody class]]){ //语言消息
        self.messageLabel.attributedText = [self voiceAttr];
    }else if ([body isKindOfClass:[EMImageMessageBody class]]){ //图片消息
        [self showImg];
    }else{
        self.messageLabel.text = @"未知类型";
    }
}

/**
 *  cell上显示图片
 */
- (void)showImg
{
   // 获取图片消息体
    EMImageMessageBody *imgBody = self.message.messageBodies[0];
    CGRect thumbnailFrame = (CGRect){0,0,imgBody.thumbnailSize};
    
    // 设置label的尺寸足够显示UIImageView
    NSTextAttachment *imgAttach = [[NSTextAttachment alloc] init];
    imgAttach.bounds = thumbnailFrame;
    NSAttributedString *imgAttri = [NSAttributedString attributedStringWithAttachment:imgAttach];
    self.messageLabel.attributedText = imgAttri;
    
    [self.messageLabel addSubview:self.chatImageView];
    
    // 设置图片控件的尺寸为缩略图的尺寸
    self.chatImageView.frame = thumbnailFrame;
    
    // 下载图片
    NSFileManager *mgr = [NSFileManager defaultManager];
    if ([mgr fileExistsAtPath:imgBody.thumbnailLocalPath]) {
        //本地路径使用fileURLWithPath
        [self.chatImageView sd_setImageWithURL:[NSURL fileURLWithPath:imgBody.thumbnailLocalPath] placeholderImage:nil];
    }else{
        [self.chatImageView sd_setImageWithURL:[NSURL URLWithString:imgBody.thumbnailRemotePath] placeholderImage:nil];
    }
}

/**
 *  返回语音富文本
 */
- (NSAttributedString *)voiceAttr
{
    // 创建一个可变的富文本
    NSMutableAttributedString *voiceAttM = [[NSMutableAttributedString alloc] init];
    
    if ([self.reuseIdentifier isEqualToString:recivierCell]) { //接收方
        // 语言图片
        UIImage *receiverImg = [UIImage imageNamed:@"chat_receiver_audio_playing_full"];
        // 图片附件
        NSTextAttachment *imgAttachment = [[NSTextAttachment alloc] init];
        imgAttachment.image = receiverImg;
        imgAttachment.bounds = CGRectMake(0, -4, 20, 20);
        // 图片富文本
        NSAttributedString *imgAtt = [NSAttributedString attributedStringWithAttachment:imgAttachment];
        [voiceAttM appendAttributedString:imgAtt];
        
        // 时间
        EMVoiceMessageBody *voiceBody = self.message.messageBodies[0];
        NSInteger duration = voiceBody.duration;
        NSString *timeStr = [NSString stringWithFormat:@"%ld",duration];
        NSAttributedString *timeAtt = [[NSAttributedString alloc] initWithString:timeStr];
        [voiceAttM appendAttributedString:timeAtt];
        
    }else{ //发送方
        
        // 时间
        EMVoiceMessageBody *voiceBody = self.message.messageBodies[0];
        NSInteger duration = voiceBody.duration;
        NSString *timeStr = [NSString stringWithFormat:@"%ld",duration];
        NSAttributedString *timeAtt = [[NSAttributedString alloc] initWithString:timeStr];
        [voiceAttM appendAttributedString:timeAtt];
        
        // 语言图片
        UIImage *receiverImg = [UIImage imageNamed:@"chat_sender_audio_playing_full"];
        NSTextAttachment *imgAttachment = [[NSTextAttachment alloc] init];
        imgAttachment.image = receiverImg;
        imgAttachment.bounds = CGRectMake(0, -4 , 20, 20);
        NSAttributedString *imgAtt = [NSAttributedString attributedStringWithAttachment:imgAttachment];
        [voiceAttM appendAttributedString:imgAtt];
    }
    
    return [voiceAttM copy];
}

@end


                
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值