iOS融云总结(一)

iOS使用融云相关用法总结:

1、融云相关配置:
    // MARK: - 配置融云
    func configureRongCloud() {
       
        /// 初始化融云
        RCIM.shared()?.initWithAppKey(RongCloudAppKery)
        
        /// 设置用户信息
        let currentUserInfo =  RCUserInfo.init(userId:"\(Caches.share.user?.id ?? 0)" , name: Caches.share.user?.nickname ?? "", portrait: Caches.share.user?.avatar ?? "")
        
        RCIM.shared()?.currentUserInfo = currentUserInfo
        
        /// 是否将用户信息和群组信息在本地持久化存储,默认值为NO
        RCIM.shared()?.enablePersistentUserInfoCache = true
        
        /// 是否在发送的所有消息中携带当前登录的用户信息,默认值为NO
//        RCIM.shared()?.enableMessageAttachUserInfo = true
        
        /// 设置状态监听
        RCIM.shared()?.connectionStatusDelegate = self
 
        /// 设置消息监听
        RCIM.shared()?.receiveMessageDelegate = self
        
        /// 是否关闭所有的本地通知,默认值是NO
        RCKitConfig.default()?.message.disableMessageNotificaiton = false
      
        if !(RCIM.shared()?.getConnectionStatus() == .ConnectionStatus_Connected) {
            
            connectRoncloud(ryToken: Caches.share.user?.ryToken ?? "")
        }
        
        // 使用名片功能时,选择联系人用到
        /// 联系人信息提供者
        RCContactCardKit.shareInstance()?.contactsDataSource = TPRCIMDataSource
        /// 群组信息提供者
        RCContactCardKit.shareInstance()?.groupDataSource = TPRCIMDataSource
        
        /// 用户信息提供者
        RCIM.shared().userInfoDataSource = TPRCIMDataSource
        /// 群组信息提供者
        RCIM.shared().groupInfoDataSource = TPRCIMDataSource
        /// 群名片信息提供者
        RCIM.shared().groupUserInfoDataSource = TPRCIMDataSource
        /// 群成员信息提供者
        RCIM.shared().groupMemberDataSource = TPRCIMDataSource
        
        //注册自定义消息
        RCIM.shared()?.registerMessageType(RCMTransferMessage.self)
        RCIM.shared()?.registerMessageType(RCMTransferReceiveMessage.self)
        RCIM.shared()?.registerMessageType(RCMRedPacketMeaasge.self)
        RCIM.shared()?.registerMessageType(RCMTipMessage.self)
        RCIM.shared()?.registerMessageType(RCMSystemMessage.self)
        RCIM.shared()?.registerMessageType(RCMGroupNotifiMessage.self)
        RCIM.shared()?.registerMessageType(RCMGroupChangeNameMessage.self)
        
        //设置圆形头像
        RCKitConfig.default()?.ui.globalMessageAvatarStyle = .USER_AVATAR_CYCLE
        RCKitConfig.default()?.ui.globalConversationAvatarStyle = .USER_AVATAR_CYCLE
        
        /// 设置SDK中全局的导航按钮字体颜色
        RCKitConfig.default()?.ui.globalNavigationBarTintColor = .OxColor333333
        
        
        //打开相册的时候可以选择视频,需要拍摄视频的话,设置成true
        RCKitConfig.default()?.message.isMediaSelectorContainVideo = false
        //关闭@功能
        RCKitConfig.default()?.message.enableMessageMentioned = false
        //开启合并转发功能
        RCKitConfig.default()?.message.enableSendCombineMessage = true
        //是否在会话页面和会话列表界面显示未注册的消息类型,默认值是 YES
        RCKitConfig.default()?.message.showUnkownMessage = true
        //消息撤回后可重新编辑的时间,单位是秒,默认值是 300s。
        RCKitConfig.default()?.message.reeditDuration = 60
    }

2、监听网络状态变化
extension AppDelegate: RCIMConnectionStatusDelegate {
    
    /**
     *  网络状态变化。
     *
     *  @param status 网络状态。
     */
    func onRCIMConnectionStatusChanged(_ status: RCConnectionStatus) {
        
        if status == .ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT {
            //被踢下线
            
            let alertVc = UIAlertController.tpAlertController(title: "下线通知", message: "您的帐号于另一台手机上登录", preferredStyle: .alert, cancelTitle: "退出", cancelActionStyle: .default, otherTitles: ["重新登录"]) { (btnIndex, action) in
                
                if btnIndex == 0 {
                    TPLog(message: "退出")
                    Caches.share.save(newUser: nil)
                    RCIM.shared()?.logout()
                    
                    DispatchQueue.main.asyncAfter(deadline: .now()) {
                        
                        let keyWindow = Global.window
                        keyWindow?.rootViewController = UINavigationController.init(rootViewController: LoginViewController())
                    }
                    
                } else {
                    
                    //重新登录
                    self.connectRoncloud(ryToken: Caches.share.user?.ryToken ?? "")
                }
            }
    
            let window = Global.window
            window?.rootViewController?.present(alertVc, animated: true, completion: nil)
            
        } else if status == .ConnectionStatus_TOKEN_INCORRECT {
            //token失效
            
            self.getRongCloudTokenAndConnect()
            
        } else if status == .ConnectionStatus_DISCONN_EXCEPTION {
            
            //与服务器的连接已断开,用户被封禁
            self.alertMessage(message: "您的帐号被封禁")
        }
    }
    
    
    /// 连接服务器
    func connectRoncloud(ryToken: String) {
        
        RCIM.shared()?.connect(withToken: ryToken, dbOpened: { (code) in
            
        }, success: { (userId) in
            
            DispatchQueue.main.async {
                
                if let w = self.window {
                    w.setupViewControlllers(delegate: self)
                }
            }
            
            
        }, error: { (status) in
            
            if (status == .RC_CONN_TOKEN_INCORRECT) {
                //从 APP 服务获取新 token,并重连
                
                self.getRongCloudTokenAndConnect()
                
            } else if(status == .RC_CONNECT_TIMEOUT) {
                //连接超时,弹出提示,可以引导用户等待网络正常的时候再次点击进行连接
                
                self.alertMessage(message: "连接超时,请稍后再试")
                
            } else {
                //无法连接 IM 服务器,请根据相应的错误码作出对应处理
                self.alertMessage(message: "无法连接 IM 服务器")
            }
            
        })
    }
    
    //获取token,并重联
    func getRongCloudTokenAndConnect() {
        
        self.request(config: ApiConfiguration.init(route: .getRyToken, params: ["":""])) { [weak self](result:Result, Error>, rawData:Data?) in
            
            switch result {
            case .success(let object):
                DispatchQueue.main.async {
                    self?.connectRoncloud(ryToken: object.data)
                }
            case .failure(let error):
                TPLog(message: "\(error.localizedDescription)")
            }
            
        }
    }
    
    
    func alertMessage(message: String) {
        
        let alertVc = UIAlertController.tpAlertController(title: "提示", message: message, preferredStyle: .alert, cancelTitle: "我知道了", cancelActionStyle: .default, otherTitles: []) { (btnIndex, action) in
            
            Caches.share.save(newUser: nil)
            RCIM.shared()?.disconnect()
            
            self.window?.rootViewController = UINavigationController.init(rootViewController: LoginViewController())
        }
        
        let window = Global.window
        window?.rootViewController?.present(alertVc, animated: true, completion: nil)
    }
    
}

3、IMKit消息接收的监听器,在此处可以设置tabbar消息红点或者其他操作。
extension AppDelegate: RCIMReceiveMessageDelegate {
    
    func onRCIMReceive(_ message: RCMessage!, left: Int32) {
       
        let unreadCount = RCIMClient.shared()?.getTotalUnreadCount() ?? 0
        
        TPLog(message: "未读消息数 \(unreadCount)")
        
        DispatchQueue.main.async {
            
            let keyWindow = Global.window
            let tabBarVC = keyWindow?.rootViewController as? UITabBarController
            
            if unreadCount > 0 {
                
                tabBarVC?.tabBar.showBadgeOnTabBarItem(index: 0, count: Int(unreadCount))
                
            } else {
                
                tabBarVC?.tabBar.hideBadgeOnTabBarItem(index: 0)
            }
            
            if let model = message.content as? RCMSystemMessage {

                var param = [String: String]()
                param["groupId"] = model.msgId

                NotificationCenter.default.post(name: NSNotification.Name(GroupDissolutionNotification), object: param)

            }
        
            if let updateGroupNameModel = message.content as? RCMGroupChangeNameMessage {
                
                NotificationCenter.default.post(name: NSNotification.Name(UpdateGroupNameSuccessNotifi), object: ["grupName":updateGroupNameModel.tipContent])
            }
        }
        
    }
   
}
4、登录成功设置用户信息,修改头像,修改昵称等更新用户信息,使用
let currentUserInfo = RCUserInfo(userId: "\(userInfo.id)" , name: userInfo.nickname, portrait: userInfo.avatar)
RCIM.shared()?.currentUserInfo = currentUserInfo
修改头像,昵称,如果使用了以下方法,会出现聊天的时候,对方看到你的用户头像,昵称还是之前的,此方法是更新SDK缓存的用户信息
 RCIM.shared().refreshUserInfoCache(RCUserInfo(userId: "\(userInfo.id)" , name: userInfo.nickname, portrait: userInfo.avatar), withUserId: "\(userInfo.id)")
5、更新好友信息,群组信息,如果不更新,会出现聊天的时候可能不会显示用户信息或群组信息
//更新好友信息
let userInfo = RCUserInfo(userId: "\(model.id)", name: (model.remark.isBlank == true) ? model.name: model.remark, portrait: model.avatar)                     
RCIM.shared()?.refreshUserInfoCache(userInfo, withUserId: "\(model.id)")
//更新群组信息
RCIM.shared()?.refreshGroupInfoCache(RCGroup(groupId: "\(model.id)", groupName: model.name, portraitUri: model.avatar), withGroupId: "\(model.id)")
6、开启或关闭群免打扰,首先需要获取群免打扰状态,然后点击开启或关闭按钮的时候,再设置会话的消息提醒状态。
/// 获取免打扰状态
    func getConversationNotifiStatus() {
        
        RCIMClient.shared()?.getConversationNotificationStatus(.ConversationType_GROUP, targetId: receiveGroupId, success: {[weak self] (nStatus) in
            
            switch nStatus {
            case .DO_NOT_DISTURB:
                self?.notifiStatus = true
            case .NOTIFY:
                self?.notifiStatus = false
            default:break
            }
            
            DispatchQueue.main.async {
                self?.tableView.reloadSections([3], with: .fade)
            }
            
        }, error: { (code) in
            self.notifiStatus = false
            DispatchQueue.main.async {
                self.tableView.reloadSections([3], with: .fade)
            }
        })
    }
    
    func setConversationNotifiStatus(isOn: Bool) {
        
        RCIMClient.shared()?.setConversationNotificationStatus(.ConversationType_GROUP, targetId: receiveGroupId, isBlocked: isOn, success: {[weak self] (nStatus) in
            
            switch nStatus {
            case .DO_NOT_DISTURB:
                self?.notifiStatus = true
            case .NOTIFY:
                self?.notifiStatus = false
            default:break
            }
            
            DispatchQueue.main.async {
                self?.tableView.reloadSections([3], with: .fade)
            }
            
        }, error: { (code) in
            
            self.notifiStatus = false
            DispatchQueue.main.async {
                self.tableView.reloadSections([3], with: .fade)
            }
        })
    }
7、清空聊天记录,清空成功后,需要发送通知或者block到会话页面进行刷新,如果不刷新,会出现数据还在,需要返回到会话列表,再次进入才会消失
// MARK: - 清空群聊聊天记录
    func clearHistoryMessage() {
        
        let latestMessages = RCIMClient.shared()?.getLatestMessages(.ConversationType_GROUP, targetId: receiveGroupId, count: 1)
        
        if latestMessages?.count ?? 0 > 0 {
        
            RCIMClient.shared()?.clearHistoryMessages(.ConversationType_GROUP, targetId: receiveGroupId, recordTime: 0, clearRemote: false, success: {
                
                DispatchQueue.main.async {
                    
                    NotificationCenter.default.post(name: NSNotification.Name(ClearMessageNotifi), object: self)
                    
                    self.showToast(text: "操作成功")
                    self.setClearMessageHistory?()
                }
                
            }, error: { (status) in
                
            })
        }
    }

// MARK: - 刷新会话页面
func refreshHistoryData() {
        
        self.conversationDataRepository.removeAllObjects()
        self.conversationMessageCollectionView.reloadData()
        
}

8、会话页面配置加号区域按钮,更新指定扩展项尝试了以后没变化,所以我采用的先全部删除,然后重新添加。

// MARK: - 配置加号区域
    func configireAddArea() {
        
        //删除原来的项
        self.chatSessionInputBarControl.pluginBoardView.removeAllItems()

        self.chatSessionInputBarControl.pluginBoardView.insertItem(UIImage(named: "xiangce"), highlightedImage: UIImage(named: "xiangce"), title: "相册", tag: Int(PLUGIN_BOARD_ITEM_ALBUM_TAG))
        
        self.chatSessionInputBarControl.pluginBoardView.insertItem(UIImage(named: "paishe"), highlightedImage: UIImage(named: "paishe"), title: "拍照", tag: Int(PLUGIN_BOARD_ITEM_CAMERA_TAG))
        
        self.chatSessionInputBarControl.pluginBoardView.insertItem(UIImage(named: "hongbao1"), highlightedImage: UIImage(named: "hongbao1"), title: "红包", tag: 20003)
        
        if self.conversationType == .ConversationType_PRIVATE {
            
            self.chatSessionInputBarControl.pluginBoardView.insertItem(UIImage(named: "zhuanzhang1"), highlightedImage: UIImage(named: "zhuanzhang1"), title: "转账", tag: 20004)
            
        } else {
            
        }
            
    
        self.chatSessionInputBarControl.pluginBoardView.insertItem(UIImage(named: "mingpian"), highlightedImage: UIImage(named: "mingpian"), title: "个人名片", tag: Int(PLUGIN_BOARD_ITEM_CARD_TAG))
            
        self.chatSessionInputBarControl.pluginBoardView.insertItem(UIImage(named: "weizhi"), highlightedImage: UIImage(named: "weizhi"), title: "位置", tag: Int(PLUGIN_BOARD_ITEM_LOCATION_TAG))
}
9、如果使用了自定义消息,那么会话页面需要注册自定义的cell,会话才会展示我们自定义的消息。
//注册单元格
        self.register(TransferAccountSendCell.self, forMessageClass: RCMTransferMessage.self)
        
        self.register(TransferAccountReceiveCell.self, forMessageClass: RCMTransferReceiveMessage.self)
        
        self.register(RedPacketSendCell.self, forMessageClass: RCMRedPacketMeaasge.self)
        
        self.register(RedPacketNotifiCell.self, forMessageClass: RCMTipMessage.self)
        
        self.register(SystemMessageCell.self, forMessageClass: RCMSystemMessage.self)
        
        self.register(GroupNotifiCell.self, forMessageClass: RCMGroupNotifiMessage.self)
        
        self.register(GroupChangeNameTipCell.self, forMessageClass: RCMGroupChangeNameMessage.self)
10、如果自定义消息,需要改变状态,比如发红包,拆红包;转账给好友,好友接受后需要改变状态,这时候可以设置 IMlib 的消息扩展听器来刷新显示。
// 消息扩展监听
RCIMClient.shared()?.messageExpansionDelegate = self

extension ChatViewController: RCMessageExpansionDelegate {
    
    func messageExpansionDidUpdate(_ expansionDic: [String : String]!, message: RCMessage!) {
        TPLog(message: "已更新")
        
        let arr:[RCMessageModel] = self.conversationDataRepository as! [RCMessageModel]
        
        if arr.count > 0 {
            
            for item in arr {
                
                if item.messageUId == message.messageUId {
                    
                    item.expansionDic = message.expansionDic
                    
                }
            }
            
            DispatchQueue.main.async {
                self.conversationMessageCollectionView.reloadData()
            }
        }
     
    }
    
    func messageExpansionDidRemove(_ keyArray: [String]!, message: RCMessage!) {
        
    }
    
    
}

11、设置接受新消息通知状态,先查询已设置的全局时间段消息提醒屏蔽;然后全局屏蔽某个时间段的消息提醒。
// MARK: -查询已设置的全局时间段消息提醒屏蔽
override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        customNaviBar.style = .whiteNoDash
        
        RCIMClient.shared()?.getNotificationQuietHours({[weak self] (startTime, spansMin) in
            
            DispatchQueue.main.async {
                if spansMin >= 1439 {
                    self?.isReceiveNotification = false
                } else {
                    self?.isReceiveNotification = true
                }
                
                self?.tableView.reloadData()
            }
            
        }, error: { (status) in
            
            DispatchQueue.main.async {
                
                self.isReceiveNotification = true
                self.tableView.reloadData()
            }
        })
    }

/*!
 全局屏蔽某个时间段的消息提醒

 @param startTime       开始消息免打扰时间,格式为 HH:MM:SS
 @param spanMins        需要消息免打扰分钟数,0 < spanMins < 1440( 比如,您设置的起始时间是 00:00, 结束时间为
 23:59,则 spanMins 为 23 * 60 + 59 = 1439 分钟。)
 @param successBlock    屏蔽成功的回调
 @param errorBlock      屏蔽失败的回调 [status:屏蔽失败的错误码]

 @discussion 此方法设置的屏蔽时间会在每天该时间段时生效。
 如果您使用 IMLib,此方法会屏蔽该会话在该时间段的远程推送;如果您使用
 IMKit,此方法会屏蔽该会话在该时间段的所有提醒(远程推送、本地通知、前台提示音)。

 @remarks 会话
 */
func setReceiveNotification(isOn: Bool) {
        
        if isOn == false {
            
            RCIMClient.shared()?.setNotificationQuietHours("00:00:00", spanMins: 1439, success: {
               
                DispatchQueue.main.async {
                    
                    self.isReceiveNotification = false
                    self.tableView.reloadData()
                }
                
            }, error: { (status) in
                
                DispatchQueue.main.async {
                    
                    self.isReceiveNotification = true
                    self.tableView.reloadData()
                }
                
            })
            
        } else {
            
            RCIMClient.shared()?.removeNotificationQuietHours({
                
                DispatchQueue.main.async {
                    
                    self.isReceiveNotification = true
                    self.tableView.reloadData()
                }
                
            }, error: { (status) in
                
                DispatchQueue.main.async {
                    
                    self.isReceiveNotification = false
                    self.tableView.reloadData()
                }
                
            })
            
        }
}
12、自定义消息,需要自定义model,自定义cell,model的类型名需要和安卓,后台统一,才能收到消息。
(1)自定义Model,需要继承RCMessageContent。
// RCMRedPacketMeaasge.h文件

#import 
#import 

/*!
 测试消息的类型名
 */
#define RCMRedPacketMeaasgeTypeIdentifier @"RC:RedPacketMsg"


NS_ASSUME_NONNULL_BEGIN

@interface RCMRedPacketMeaasge : RCMessageContent

/** 红包个数 */
@property (nonatomic, copy) NSString * packetCount;
/** 红包备注 */
@property (nonatomic, copy) NSString * remark;
/** 发送者ID */
@property (nonatomic, copy) NSString * sendUserId;
/** 后台生成的红包id */
@property (nonatomic, copy) NSString * redPacketId;

/*!
 初始化测试消息

 @param content 文本内容
 @return        测试消息对象
 */
+ (instancetype)messageWithContent:(NSString *)content;

@end

NS_ASSUME_NONNULL_END

// RCMRedPacketMeaasge.m文件

#import "RCMRedPacketMeaasge.h"

@implementation RCMRedPacketMeaasge
///初始化
+ (instancetype)messageWithContent:(NSString *)content {
    
    RCMRedPacketMeaasge *text = [[RCMRedPacketMeaasge alloc] init];
    if (text) {
        
    }
    return text;
}

///消息是否存储,是否计入未读数
+ (RCMessagePersistent)persistentFlag {
    return  MessagePersistent_ISCOUNTED;
}

/// NSCoding
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        self.redPacketId = [aDecoder decodeObjectForKey:@"redPacketId"];
        self.packetCount = [aDecoder decodeObjectForKey:@"packetCount"];
        self.sendUserId = [aDecoder decodeObjectForKey:@"sendUserId"];
        self.remark = [aDecoder decodeObjectForKey:@"remark"];

    }
    return self;
}

/// NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.redPacketId forKey:@"redPacketId"];
    [aCoder encodeObject:self.packetCount forKey:@"packetCount"];
    [aCoder encodeObject:self.sendUserId forKey:@"sendUserId"];
    [aCoder encodeObject:self.remark forKey:@"remark"];

}


///将消息内容编码成json
- (NSData *)encode {
    NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];
    [dataDict setObject:self.redPacketId forKey:@"redPacketId"];
    [dataDict setObject:self.packetCount forKey:@"packetCount"];
    [dataDict setObject:self.sendUserId forKey:@"sendUserId"];
    [dataDict setObject:self.remark forKey:@"remark"];

    if (self.senderUserInfo) {
        [dataDict setObject:[self encodeUserInfo:self.senderUserInfo] forKey:@"user"];
    }

    NSData *data = [NSJSONSerialization dataWithJSONObject:dataDict options:kNilOptions error:nil];
    return data;
}

///将json解码生成消息内容
- (void)decodeWithData:(NSData *)data {
    if (data) {
        __autoreleasing NSError *error = nil;

        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        NSLog(@"sysDic----%@",dictionary);
        
        if (dictionary) {
            self.redPacketId = dictionary[@"redPacketId"];
            self.sendUserId = dictionary[@"sendUserId"];
            self.packetCount = dictionary[@"packetCount"];
            self.remark = dictionary[@"remark"];
            
            NSDictionary *userinfoDic = dictionary[@"user"];
            [self decodeUserInfo:userinfoDic];
        }
    }
}

/// 会话列表中显示的摘要
- (NSString *)conversationDigest {
    
    RCUserInfo * info = [RCIM sharedRCIM].currentUserInfo;
    if ([self.sendUserId isEqualToString: info.userId]) {
        return [NSString stringWithFormat:@"[红包] %@", self.remark];
    } else {
        return [NSString stringWithFormat:@"[红包] %@", self.remark];
    }
    return @"[红包]";
}

///消息的类型名
+ (NSString *)getObjectName {
    return RCMRedPacketMeaasgeTypeIdentifier;
}


@end

(2)自定义消息之cell
//红包(发)
import UIKit


class RedPacketSendCell: RCMessageCell {
    
    override init!(frame: CGRect) {
        super.init(frame: frame)
        
        setupView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override class func size(for model: RCMessageModel!, withCollectionViewWidth collectionViewWidth: CGFloat, referenceExtraHeight extraHeight: CGFloat) -> CGSize {
        
        
        var height: CGFloat = 103.0
    
        height += extraHeight
        
        return CGSize(width: collectionViewWidth, height: height)
    }
    
    override func setDataModel(_ model: RCMessageModel!) {
        
        super.setDataModel(model)
        
        let expandDic = model.expansionDic
        
//        var idArr = [String]()
        var isExpire = ""
        
        var receiveIndex = 0
        
        if expandDic?.count ?? 0 > 0 {
            
            receiveIndex = (expandDic?.count ?? 0) - 1
            
            isExpire = expandDic?["isExpire"] ?? ""
            
//            TPLog(message: "receiveIndex ---- \(receiveIndex)")
//            TPLog(message: "count ---- \(expandDic?.count ?? 0)")
            
            /*
            //拆红包的用户ID
            let idStr = String("\(expandDic?["receiveIds"] ?? "")")
            isExpire = expandDic?["isExpire"] ?? ""
            if idStr.count > 0 {
                idArr = idStr.components(separatedBy: ",")
            } else {
                
            }
 */
        }
        
        
        let messageModel = model.content as! RCMRedPacketMeaasge
        remarkLabel.text = messageModel.remark
        
        if self.messageDirection == .MessageDirection_RECEIVE {
            
            self.messageContentView.frame = CGRect(x: 0, y: 0, width: RelativeScreen.width*0.66, height: 93)
            
//            self.messageContentView.frame = CGRect(x: 0, y: 0, width: self.messageContentView.frame.size.width, height: 93)
            
            if receiveIndex > 0 {
                
                //判断红包是否被领完
                if Int(messageModel.packetCount) == receiveIndex {
                    
                    let receiveUsderId = expandDic?["\(Caches.share.user?.id ?? 0)"] ?? ""
                    
                    if receiveUsderId.isBlank == false {
                        
                        statusLabel.text = "已领取"
                        bgView.backgroundColor = .OxColorFBD6B5
                        typeLabel.textColor = .OxColorFFFFFF
                        
                    } else {
                        
                        statusLabel.text = "已被领完"
                        bgView.backgroundColor = .OxColorFBD6B5
                        typeLabel.textColor = .OxColorFFFFFF
                    }
                    
                    
                    
                } else {
                    //判断红包是否已过期
                    if isExpire == "1" {
                        
                        statusLabel.text = "已过期"
                        bgView.backgroundColor = .OxColorFBD6B5
                        typeLabel.textColor = .OxColorFFFFFF
                        
                    } else {
                     
                        //判断领取人ids是否包含当前用户
                        let receiveUsderId = expandDic?["\(Caches.share.user?.id ?? 0)"] ?? ""
                        
                        if receiveUsderId.isBlank == false {
                            
                            statusLabel.text = "已领取"
                            bgView.backgroundColor = .OxColorFBD6B5
                            typeLabel.textColor = .OxColorFFFFFF
                            
                        } else {
                            
                            statusLabel.text = ""
                            bgView.backgroundColor = .OxColorF99B3E
                        }
                    }
                }
             
            } else {
                
                statusLabel.text = ""
                bgView.backgroundColor = .OxColorF99B3E
                
            }
            
        } else {
            
            self.messageContentView.frame = CGRect(x: 0, y: 0, width: RelativeScreen.width*0.66, height: 103)
            
            if receiveIndex > 0 {
                
                //判断红包是否被领完
                if Int(messageModel.packetCount) == receiveIndex {
                    
                    let receiveUsderId = expandDic?["\(Caches.share.user?.id ?? 0)"] ?? ""
                    
                    if receiveUsderId.isBlank == false {
                        
                        statusLabel.text = "已领取"
                        bgView.backgroundColor = .OxColorFBD6B5
                        typeLabel.textColor = .OxColorFFFFFF
                        
                    } else {
                        
                        statusLabel.text = "已被领完"
                        bgView.backgroundColor = .OxColorFBD6B5
                        typeLabel.textColor = .OxColorFFFFFF
                    }
                    
                } else {
                    //判断红包是否已过期
                    if isExpire == "1" {
                        
                        statusLabel.text = "已过期"
                        bgView.backgroundColor = .OxColorFBD6B5
                        typeLabel.textColor = .OxColorFFFFFF
                        
                    } else {
                     
                        //判断领取人ids是否包含当前用户
                        let receiveUsderId = expandDic?["\(Caches.share.user?.id ?? 0)"] ?? ""
                        
                        if receiveUsderId.isBlank == false {
                            
                            statusLabel.text = "已领取"
                            bgView.backgroundColor = .OxColorFBD6B5
                            typeLabel.textColor = .OxColorFFFFFF
                            
                        } else {
                            
                            statusLabel.text = ""
                            bgView.backgroundColor = .OxColorF99B3E
                        }
                    }
                }
             
            } else {
                
                statusLabel.text = ""
                bgView.backgroundColor = .OxColorF99B3E
                
            }
        }
        
    }
    
    // MARK: - setupViews
    func setupView() {
        
        self.messageContentView.addSubview(bgView)
        bgView.addSubview(iconImageView)
        bgView.addSubview(remarkLabel)
        bgView.addSubview(statusLabel)
        bgView.addSubview(lineView)
        bgView.addSubview(typeLabel)
        
        bgView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        iconImageView.snp.makeConstraints { (make) in
            make.top.equalTo(16)
            make.left.equalTo(14)
            make.width.height.equalTo(30)
        }
        
        remarkLabel.snp.makeConstraints { (make) in
            make.top.equalTo(iconImageView)
            make.left.equalTo(iconImageView.snp.right).offset(10)
            make.right.equalTo(-14)
        }
        
        statusLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(remarkLabel)
            make.top.equalTo(remarkLabel.snp.bottom).offset(4)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.top.equalTo(iconImageView.snp.bottom).offset(11)
            make.left.equalTo(11)
            make.right.equalTo(-17)
            make.height.equalTo(1)
        }
        
        typeLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(lineView)
            make.top.equalTo(lineView.snp.bottom).offset(7)
            make.bottom.equalTo(-12)
        }
        
        self.bubbleBackgroundView.isUserInteractionEnabled = true

        let singleTap = UITapGestureRecognizer.init(target: self, action: #selector(tapMessage(sender:)))
        self.bgView.addGestureRecognizer(singleTap)
        
    }
    
    @objc func tapMessage(sender: UITapGestureRecognizer) {
 
        self.delegate.didTapMessageCell?(self.model)
    }
    
    
    // MARK: - lazy object
    lazy var bgView: UIView = {
        let view = UIView()
        view.backgroundColor = .OxColorF99B3E
        view.clipsToBounds = true
        view.layer.cornerRadius = 8.0
        return view
    }()
    
    lazy var iconImageView: UIImageView = {
        let imageV = UIImageView()
        imageV.image = UIImage(named: "redpacket")
        return imageV
    }()
    
    lazy var remarkLabel: UILabel = {
        let label = UILabel.tpLabel(textColor: .OxColorFFFFFF, font: .BoldFont16, textAlignment: .left)
        label.text = "恭喜发财,大吉大利"
        return label
    }()
    
    lazy var statusLabel: UILabel = {
        let label = UILabel.tpLabel(textColor: .OxColorFFFFFF, font: .MediumFont12, textAlignment: .left)
        label.text = "已领取"
        return label
    }()
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .OxColorFFFFFF
        view.alpha = 0.5
        return view
    }()
    
    lazy var typeLabel: UILabel = {
        let label = UILabel.tpLabel(textColor: .OxColorFBD7B6, font: .MediumFont15, textAlignment: .left)
        label.text = "红包"
        return label
    }()
    
    
    
}

(3)发送自定义消息
    // MARK: - 发送红包消息
    func sendRedpacketMessage() {
        
        let msg = RCMRedPacketMeaasge.init()
        msg.sendUserId = "\(self.user?.id ?? 0)"
        msg.redPacketId = "\(self.redpacketModel?.redPackageID ?? 0)"
        
        if self.type == .personal {
            msg.packetCount = "1"
        } else {
            msg.packetCount = headView.countTf.text ?? "0"
        }
        msg.remark = (headView.textView.text.isBlank == true) ? "恭喜发财,大吉大利" : headView.textView.text
        
        
        let rcMsg = RCMessage()
        rcMsg.canIncludeExpansion = true
        rcMsg.content = msg
        
        if self.type == .personal {
            rcMsg.conversationType = .ConversationType_PRIVATE
        } else {
            rcMsg.conversationType = .ConversationType_GROUP
        }

        rcMsg.targetId = receivetargetId
        rcMsg.messageDirection = .MessageDirection_SEND
        rcMsg.messageId = 0
        
        var param = [String: String]()
//        param["receiveIds"] = "" //是否领取过红包
        param["isExpire"] = "0" //是否已过期

        rcMsg.expansionDic = param
        
        RCIM.shared()?.send(rcMsg, pushContent: "", pushData: "", successBlock: { (successMsg) in
            
            if let model = successMsg {
                
                TPLog(message: "发送成功:\(model.expansionDic)")

                DispatchQueue.main.async {
                    self.navigationController?.popViewController(animated: true)
                }
            }
            
            
            
        }, errorBlock: { (code, errorMsg) in
            
            TPLog(message: "发送失败:\(code) --- \(errorMsg)")
        })
    }
    
}

你可能感兴趣的:(iOS融云总结(一))