通过apicloud开发app,集成融云的sdk开发IM聊天系统

1初始化融云,显示聊天列表
var rong
var header_h = 50
var footer_h = 45
var toUserId;
var token;apiready = function() {token = $api.getStorage("local_user").token;rong = api.require('rongCloud2');
rong.init(function(ret, err) {
if (ret.status == 'error') {
// viewErr(err.code)
}
});
rong.setConnectionStatusListener(function(ret, err) {
viewErr(ret.result.code)
if (ret.result.code == 6) {
reloginIm();
}
sendEvent('imConStatus', {
code : ret.result.code
})
});
rong.setOnReceiveMessageListener(function(ret, err) {
api.sendEvent({
name : 'getNewMes',
extra : {
data : ret.result.message
}
})
})
rong.connect({
token : token
}, function(ret, err) {
if (ret.status == 'success') {
api.toast({
msg : "连接成功"
});
getLast();
} else {
// api.toast({
// msg : JSON.stringify(err)
// });
}
});
getEvent('sendMsg', function(data) {
sendMsg(data.msg)
})
getEvent('sendImgMsg', function(data) {
sendImgMsg(data.path)
})
getEvent('sendVoiceMsg', function(data) {
sendVoiceMsg(data.path, data.duration)
})
getEvent('hisList', function(data) {
hisList();
})
getEvent('loginOrOut', function(data) {
reLoginIm();
})
}function hisList(msgid) {
rong.getLatestMessages({
conversationType : 'PRIVATE',
targetId : toUserId,
count : 10
}, function(ret, err) {
sendEvent('viewHisList', {
result : ret.result
})
})
}function sendMsg(msg) {
rong.sendTextMessage({
conversationType : 'PRIVATE',
targetId : toUserId,
text : msg,
extra : ''
}, function(ret, err) {
sendCallBack(ret, err)
});
}function sendImgMsg(imgPath) {
rong.sendImageMessage({
conversationType : 'PRIVATE',
targetId : toUserId,
imagePath : imgPath,
extra : ''
}, function(ret, err) {
sendCallBack(ret, err)
});
}function sendVoiceMsg(voicePath, duration) {
rong.sendVoiceMessage({
conversationType : 'PRIVATE',
targetId : toUserId,
voicePath : voicePath,
duration : duration,
extra : ''
}, function(ret, err) {
sendCallBack(ret, err)
});
}function sendCallBack(ret, err) {
if (ret.status == 'prepare') {
sendEvent("viewMsg", {
result : ret.result.message,
status : ret.status
})
} else {
sendEvent("viewMsg", {
status : ret.status,
messageId : ret.result.message.messageId,
err : err
})
}
}//点击用户进入页面开始聊天
function imOpen(imId) {
toUserId = imId;
var num = $(".pppp4").text();
ajax('doctorManage/scImg', {
id : imId
}, function(rets, err) {
$api.setStorage("local_us", rets.result.user);
})
api.openWin({
name : 'imMain',
url : 'widget://html/qm/imMain.html',
pageParam : {
toUserId : imId,
dateSize : dateSize,
num : num,
sbName : sbName,
InternetType : InternetType
}});}function getLast() {
rong.getConversationList(function(ret, err) {
//将获得的数据插入到容器中
if (ret.result != undefined) {}}
})
}
2UI页面主要控制聊天窗口样式
var header_h = 59
var footer_h = 35
var uicInit = 0;
var UIChatBox;
apiready = function() {
$("#page_title").append($api.getStorage("local_us").realname);var $header = $api.dom('header');
$api.fixStatusBar($header);
header_h = $api.offset($header).h;
UIChatBox = api.require('UIChatBox');
uic()
UIChatBox.addEventListener({
target : 'inputBar',
name : 'move'
}, function(ret, err) {
ucbChange(ret)
});
UIChatBox.addEventListener({
target : 'inputBar',
name : 'change'
}, function(ret, err) {
if (uicInit == 0) {
uicInit = 1
} else {
ucbChange(ret)
}
});
UIChatBox.addEventListener({
target : 'recordBtn',
name : 'press'
}, function(ret, err) {
openTip('recordStart')
api.startPlay({
path : 'widget://image/im/sound/play_voice.mp3'
}, function() {
api.startRecord();
});
});
UIChatBox.addEventListener({
target : 'recordBtn',
name : 'press_cancel'
}, function(ret, err) {
api.closeFrame({
name : 'recordStart'
});
setTimeout(function() {
api.stopRecord(function(ret, err) {
if (ret.duration == 0) {
openTip('recordError')
setTimeout(function() {
api.closeFrame({
name : 'recordError'
});
}, 500)
} else {
sendEvent('sendVoiceMsg', {
path : ret.path,
duration : ret.duration
})
}
api.startPlay({
path : 'widget://image/im/sound/stop_voice.mp3'
});
});
}, 300)
});
UIChatBox.addEventListener({
target : 'recordBtn',
name : 'move_out'
}, function(ret, err) {
api.closeFrame({
name : 'recordStart'
});
openTip('recordChange')
});
UIChatBox.addEventListener({
target : 'recordBtn',
name : 'move_out_cancel'
}, function(ret, err) {
api.closeFrame({
name : 'recordChange'
});
api.stopRecord(function(ret, err) {});
});
UIChatBox.addEventListener({
target : 'recordBtn',
name : 'move_in'
}, function(ret, err) {
api.closeFrame({
name : 'recordChange'
});
openTip('recordStart')
});
randomSwitchBtn(document.getElementById("asd"), 'cloud', 0)
};
function openTip(name) {
api.openFrame({
name : name,
url : 'widget://html/qm/' + name + '.html',
rect : {
y : (api.winHeight - 200 - 35) / 2,
x : (api.winWidth - 200 ) / 2,
w : 200,
h : 200
},
hScrollBarEnabled : false,
vScrollBarEnabled : false
});
}function ucbChange(ret) {
var _h = ret.inputBarHeight + ret.panelHeight;
var h = api.winHeight - header_h - _h;
if (ret.panelHeight != 0) {
// h = h - 35
}
api.setFrameAttr({
name : "imIndex",
rect : {
x : 0,
y : header_h,
w : 'auto',
h : h
},
bounces : true
});
setBottom();
}function setBottom() {
api.execScript({
frameName : 'imIndex',
script : 'down();'
});
}function uic() {
UIChatBox.open({
placeholder : '',
maxRows : 4,
emotionPath : 'widget://image/im/uic/emotion',
texts : {
recordBtn : {
normalTitle : '按住 说话',
activeTitle : '松开 结束'
}
},
styles : {
inputBar : {
borderColor : '#d9d9d9',
bgColor : '#f2f2f2'
},
inputBox : {
borderColor : '#B3B3B3',
bgColor : '#FFFFFF'
},
emotionBtn : {
normalImg : 'widget://image/im/uic/face1.png'
},
extrasBtn : {
normalImg : 'widget://image/im/uic/add1.png'
},
keyboardBtn : {
normalImg : 'widget://image/im/uic/key1.png'
},
speechBtn : {
normalImg : 'widget://image/im/uic/voice.png'
},
recordBtn : {
normalBg : '#c4c4c4',
activeBg : '#999999',
color : '#000',
size : 14
},
indicator : {
target : 'both',
color : '#c4c4c4',
activeColor : '#9e9e9e'
}
},
extras : {
titleSize : 10,
titleColor : '#a3a3a3',
btns : [{
title : '图片',
normalImg : 'widget://image/im/uic/album1.png',
activeImg : 'widget://image/im/uic/album2.png'
}, {
title : '拍照',
normalImg : 'widget://image/im/uic/cam1.png',
activeImg : 'widget://image/im/uic/cam2.png'
}]
}
}, function(ret) {
//点击附加功能面板
if (ret.eventType == 'clickExtras') {
if (ret.index == 0) {
api.getPicture({
sourceType : 'library',
allowEdit : true,
quality : 50,
targetWidth : 1000,
targetHeight : 1000
}, function(ret, err) {
if (ret && ret.data) {
sendEvent('sendImgMsg', {
path : ret.data
})
} else {
// alert('你没有选择图片')
api.toast({
msg : '你没有选择图片',
location : 'middle'
})
}})
}
if (ret.index == 1) {
api.getPicture({
sourceType : 'camera',
allowEdit : true,
quality : 50,
targetWidth : 1000,
targetHeight : 1000
}, function(ret, err) {if (ret && ret.data) {
sendEvent('sendImgMsg', {
path : ret.data
})
} else {
// alert('你没有选择图片')
api.toast({
msg : '你没有选择图片',
location : 'middle'
})
}})
}
}
//点击发送按钮
if (ret.eventType == 'send') {
sendEvent('sendMsg', {
msg : ret.msg
})
}
});
}// 随意切换按钮
function randomSwitchBtn(obj, name, index) {
api.openFrame({
name : "imIndex",
url : "widget://html/qm/imIndex.html",
pageParam : {
toUserId : api.pageParam.toUserId
},
rect : {
x : 0,
y : header_h,
w : 'auto',
h : api.winHeight - header_h - footer_h
}
});
}
3实时聊天数据显示页面JS
var toUserIdvar emotionData;
apiready = function() {
//存储表情getImgsPaths("widget://image/im/uic/emotion/emotion", function(emotion) {
emotionData = emotion;
})
toUserId = (api.pageParam.toUserId)
getEvent('viewMsg', function(ret) {
if (ret.status == 'prepare') {
disMsg(ret.result)
} else if (ret.status == 'success') {
$("#imSendStatus_" + ret.messageId).empty()
} else if (ret.status == 'error') {
$("#imSendStatus_" + ret.messageId).empty().append("<img src='../../image/im/im_send_error.gif'>")
//alert(JSON.stringify(ret.err))
}
})
getEvent('getNewMes', function(ret) {
if (ret.data.targetId == toUserId) {
disMsg(ret.data)
}
})
getEvent('viewHisList', function(ret) {
disHisMsg(ret.result);
})
getEvent('imConStatus', function(ret) {
viewErr(ret.code)
sendEvent('loginOrOut', {})
})
sendEvent('hisList', {})
}
function down() {
setTimeout(function() {
document.getElementsByTagName('body')[0].scrollTop = document.getElementsByTagName('body')[0].scrollHeight;
}, 200)
}function disHisMsg(items) {
try {
for ( inx = 0; inx < items.length; inx++) {
$("#messageList").prepend(msgView(items[inx], 1))
down();
}
} catch(e) {
sendEvent('hisList', {})
}
}function disMsg(item) {
$("#messageList").append(msgView(item))
down();
}/*** {content: {text: 'Hello world!',extra: ''}, // 消息内容conversationType: 'PRIVATE', // 参见 会话类型 枚举messageDirection: 'SEND', // 消息方向:SEND 或者 RECEIVEtargetId: '55', // 这里对应消息发送者的 userIdobjectName: 'RC:TxtMsg', // 消息类型,参见 http://docs.rongcloud.cn/android_message.html#_内置内容类消息sentStatus: 'SENDING', // 发送状态:SENDING, SENT 或 FAILEDsenderUserId: '55', // 发送者 userIdmessageId: 608, // 本地消息 IdsentTime: 1418971531533, // 发送消息的时间戳,从 1970 年 1 月 1 日 0 点 0 分 0 秒开始到现在的毫秒数receivedTime: 0 // 收到消息的时间戳,从 1970 年 1 月 1 日 0 点 0 分 0 秒开始到现在的毫秒数}*/
function msgView(item, timeGenre) {
var htm = '';
if (item.sentStatus != 'FAILED') {
var className = ''
var userLogo = '../../image/im/face1.png'
var msg = '';
var imSendStatus = ''
var imVcImg = ''
switch(item.messageDirection) {
case 'SEND':
className = 'sender'
imVcImg = 'to'
userLogo =  sys_base_url+ $api.getStorage("local_user").Idimg;
break;
case 'RECEIVE':
className = 'receiver'
imVcImg = 'from'
userLogo = sys_base_url+$api.getStorage("local_us").Idimg;
break;
}
switch(item.sentStatus) {
case 'SENDING':
imSendStatus = "<img src='../../image/im/im_send.jpg'>"
break;
case 'SENT':
break;
case 'FAILED':
imSendStatus = "<img src='../../image/im/im_send_error.jpg'>"
break;
}
switch(item.objectName) {
case 'RC:TxtMsg':
msg = item.content.text;
msg = transText(msg);
msg = " <span>" + msg + "</span>"
break;
case 'RC:ImgMsg':
if (item.content.localPath) {
msg = "<img src='" + item.content.localPath + "' width='100px'>"
} else {
msg = "<img src='" + item.content.imageUrl + "' width='100px'>"
}
msg = " <span>" + msg + "</span>"
break;
case 'RC:VcMsg':
if (item.content.voicePath) {
msg = " <span οnclick=\"voicePlay('" + item.content.voicePath + "',this)\"><img height=\"16px\" id='imVice" + item.messageId + "' src=\"../../image/im/" + imVcImg + "_voice.png\" oldsrc=\"" + imVcImg + "\"><span>" + item.content.duration + "\"</span></span>"
} else {
// alert(JSON.stringify(item))
}
break;
}
var imTimeArgs = commDateView(item.sentTime)
if (timeGenre) {
$("#time" + imTimeArgs[0]).remove()
}
if ($("#time" + imTimeArgs[0]).length == 0) {
htm += "<div class=\"imtime\" id=\"time" + imTimeArgs[0] + "\">" + imTimeArgs[1] + "</div>"
}
htm += "<div class=\"" + className + "\">";
htm += "<div class=\"avatar\">";
htm += " <img src=\"" + userLogo + "\">";
htm += "</div>"
htm += "<div class=\"cont\">";
htm += " <div class=\"triangle\"></div>";
htm += msg;
htm += " <div id=\"imSendStatus_" + item.messageId + "\" class=\"status\">";
htm += imSendStatus;
htm += " </div>";
htm += "</div>";
htm += "</div>";
}
return htm
}var play_id = []
function voicePlay(voicePath, item) {
var imgGenre = $(item).children("img").attr('oldsrc')
var imgId = $(item).children("img").attr('id')
if (play_id.length == 0) {
play_id[0] = imgGenre;
play_id[1] = imgId;
$(item).children("img").attr('src', '../../image/im/' + imgGenre + '_voice.gif')
api.startPlay({
path : voicePath
}, function() {
$(item).children("img").attr('src', '../../image/im/' + imgGenre + '_voice.png')
play_id = [];
});
} else {
api.stopPlay();
$("#" + play_id[1]).attr('src', '../../image/im/' + play_id[0] + '_voice.png')
if (play_id[1] != imgId) {
play_id = [];
voicePlay(voicePath, item)
} else {
play_id = [];
}
}
}function transText(text, imgWidth, imgHeight) {
var imgWidth = imgWidth || 16;
var imgHeight = imgHeight || 16;
var regx = /\[(.*?)\]/gm;
var textTransed = text.replace(regx, function(match) {
var imgSrc = emotionData[match];
if (!imgSrc) {
//说明不对应任何表情,直接返回
return match;
}
var img = "<img src=" + imgSrc + " width=" + imgWidth + " height=" + imgHeight + ">";
return img;
});
return textTransed;
}function getImgsPaths(sourcePathOfChatBox, callback) {
var jsonPath = sourcePathOfChatBox + ".json";
api.readFile({
path : jsonPath
}, function(ret, err) {
if (ret.status) {
var emotionArray = JSON.parse(ret.data);
var emotion = {};
for (var idx in emotionArray) {
var emotionItem = emotionArray[idx];
var emotionText = emotionItem["text"];
var emotionUrl = "../../image/im/uic/emotion/" + emotionItem["name"] + ".png";
emotion[emotionText] = emotionUrl;
}
/* 把 emotion对象 回调出去. */
if ("function" === typeof (callback)) {
callback(emotion);
}
}
});
}

记录一下融云即时通讯IM相关推荐

  1. 融云即时通讯SDK集成 – 定制UI(二) ——添加自定义表情库

    融云即时通讯SDK集成 – 定制UI(二) --添加自定义表情库 背景: 最近公司新上的app要加上即时通讯的功能, 自己快速实现一个当然是不可能的了(项目deadline也顶不住哇).就从各家成熟的 ...

  2. 融云即时通讯云平台获北京六局委新技术新产品认证

    近日,融云即时通讯云平台成功入选第七批北京市新技术新产品(服务)认证,成为本批次中即时通讯行业唯一入选企业.该证书是由北京市科学技术委员会.北京市发展改革委员会.北京市经济和信息化委员会.北京市住房和 ...

  3. iOS开发融云即时通讯集成详细步骤

    1.融云即时通讯iOS SDK下载地址   http://rongcloud.cn/downloads  选择iOS   SDK下载 2.进行应用开发之前,需要先在融云开发者平台创建应用,如果您已经注 ...

  4. 融云即时通讯云5大高级功能解决App运营诸多痛点

    在移动互联网时代,涉及各类民生的App应用已经彻底改变了人们的生活方式.据工信部日前发布的<2017年上半年我国互联网业务运行情况报告>显示,我国移动应用程序,即App的数量已超402万款 ...

  5. 对接融云即时通讯组件SDK,轻松实现App聊天室

    我好像特别喜欢做聊天室类的东东,刚折腾完微软的SignalR又折腾App.本来想研究研究XMPP的,由于服务器的搭建问题,先采用一个第三方的吧,看看效果如何.听到弟弟说他们公司用到了融云,我也下载个S ...

  6. iOS:融云即时通讯快速集成

    一.介绍 即时通讯在众多社交软件.生活软件以及教育软件中已经是必备的功能了,在当前国内,即时通讯SDK做的比较不错的有那么几家,例如环信SDK.融云SDK...,这两家做的都很不错,各有千秋吧,要是真 ...

  7. 融云聊天 php_thinkphp整合系列之融云即时通讯在线聊天

    随着技术的发展:现代的网站:越来越趋于应用形式了: 不再是像以前那样需要用户刷新页面:获取数据了: 服务器端可以主动向用户推送数据:更加及时性了: 比较突出的就是即时通讯在线聊天: 今个:我们要打造的 ...

  8. 融云即时通讯后续:产品需求与融云的碰撞

    产品需求与融云的碰撞 一.融云聊天消息推送功能 产品需求:多端同步登录,消息同步,且多端能同步收到消息推送 融云目前实现的功能:多个APP消息同步,应用在前台能同时收到消息(我在溜达和卖家端都能即时收 ...

  9. 融云即时通讯SDK集成 -- 定制UI(二) ——添加自定义表情库

    背景: 最近公司新上的app要加上即时通讯的功能, 自己快速实现一个当然是不可能的了(项目deadline也顶不住哇).就从各家成熟的SDK厂商选来选去的, 各有各的好也各有各的不足.最后点兵点将,选 ...

最新文章

  1. python如何处理异常_python如何进行异常处理
  2. JS 总结之事件循环
  3. Java中的static
  4. C++Binomia distribution二项分布的实现算法(附完整源码)
  5. JavaScript 与java中数组的区别
  6. 安装这些App的注意了!隐私窃取 捆绑推广 已被下架 现在卸载还来得及!
  7. 服务器好玩的项目_听说女神还没买到回家的车票,程序员小P偷偷架起了服务器...
  8. hdu1215七夕节
  9. PphpStorm常用操作整理
  10. VB.NET与Access数据库如何建立连接
  11. 计算机专业需要外语口试,计算机专业英语词汇大全,计算机专业必读英语词汇!...
  12. 大众点评有多少用户2019_2019全国大众点评网数据下载获取
  13. html短期总结(至表单)
  14. 武汉大学计算机学院 优秀夏令营,武汉大学计算机学院2016年优秀大学生暑期夏令营活动实施方案...
  15. 计算机博士差国际期刊能申请答辩吗,博士生申请答辩注意事项
  16. uwsgi graceful reload
  17. 转型之路之Excel单元格按数值显示带背景颜色进度条
  18. 2020芝加哥计算机博士生录取,2020年芝加哥大学博士面试后多久知道结果
  19. 一个好领导,懂得为下属“打伞”
  20. java基础(部分)

热门文章

  1. VUE实现Web端多人语音视频聊天
  2. 如何制定好的串口通信的指令通讯协议
  3. uniapp实现下拉搜索选择框,app,h5可用
  4. 工业软件中的EDA软件名单
  5. PMP五大过程组与十大知识领域(九五之尊图)
  6. 关于通达OA精灵的一点心得
  7. mysql基础(2)mysql基础知识
  8. WAMP的安装与配置
  9. 二手房---如何砍价(防坑笔记二)
  10. 几款截图软件分析,拷屏,切图和粘贴