bmob能做bmob数据实时同步对战吗

Unity3D(11)
1、官方文档
2、官方文档2
1、注册bmob账号
2、后台创建应用,然后点击应用创建表
&& 创建一张表,如表名MyTable
&& 然后在表里创建字段列,如:
&& 姓名:playername,分数:score
3、获取密钥Application ID和REST API key,下载SDK
&& SDK下载:
&& Demo下载:
4、在Unity导入bmob
在你的项目Assets根目录下创建&libs&目录,将下载的BmobSDK(也就是Bmob-Unity.dll)文件放入该目录下
5、初始化BmobSDK
&& 选中摄像机,把BmobUnity对象拖拽到摄像机上,然后在属性窗口中设置 ApplicationId 和 RestKey 。
6、创建表的对应模型类
创建一个脚本类,让它与你在bmob后台创建的表相对应,以理解为表的一个模型,该类需要继承自BmobTable,并实现字段的读写方法。(其实就是用来操作表的)
using UnityE
using System.C
using cn.bmob.
public class MyGameTable : BmobTable
//以下对应云端表的字段名称
public BmobInt score { }
public string playername { }
//读字段信息
public override void readFields(BmobInput input)
base.readFields(input);
this.score = input.getInt(&score&);
this.playername = input.getString(&playername&);
//写字段信息
public override void write(BmobOutput output, bool all)
base.write(output, all);
output.Put(&score&, this.score);
output.Put(&playername&, this.playername);
7、操作数据
这里只列举了插入数据,查询数据,更改数据的方法,其它方法参照官方文档
using System.C
using System.Collections.G
using UnityE
using cn.bmob.
using cn.bmob.
using cn.bmob.
using System.N
using cn.bmob.
using cn.bmob.
using cn.bmob.E
public class HelloBomb : MonoBehaviour {
private BmobU
void Start () {
//注册调试打印对象,这样才能用print方法
BmobDebug.Register(print);
//下面这句不知道什么意思,没有也可以
BmobDebug.level = BmobDebug.Level.TRACE;
//获取到组件
bmob = GetComponent&BmobUnity&();
void Update () {
if (Input.GetKeyDown(KeyCode.C))
if (Input.GetKeyDown(KeyCode.G))
//云端表的名字
string tableName = &MyGameTable&;
//添加数据
void Create()
//创建数据对象
MyGameTable data = new MyGameTable();
data.score = Random.Range(0, 100);
data.playername = &zhangsan&;
//往表“MyGameTable”里添加一行数据data,
bmob.Create(tableName, data, (resp, exception) =&
if (exception != null)
//如果添加失败,输出错误原因
print(&保存失败, 失败原因为: & + exception.Message);
//如果添加成功,输出创建的是时间
print(&保存成功, @& + resp.createdAt);
//获取数据
void Get()
bmob.Get&MyGameTable&(tableName, &&, (resp, exception) =&
if (exception != null)
print(&查询失败, 失败原因为: & + exception.Message);
MyGameTable game =
print(&获取的对象为: & + game.ToString());
print(game.playername);
//更改数据
void ChangeTable()
MyGameTable game = new MyGameTable();
game.playername = &pn_123&;
bmob.Update(tableName, &&, game, (resp, exception) =&
if (exception != null)
print(&保存失败, 失败原因为: & + exception.Message);
print(&保存成功, @& + resp.updatedAt);
备注:其它一些搭建服务器手段
1、大型服务器:用node.js+MySql搭建
2、轻量级服务器wamp,可以把自己电脑用作服务器,集成了各种服务器需要的环境,安装完成就可以使用,但是如果需要外网(不是局域网)访问,就需要用其它软件提供域名映射
3、如果是做Unity局域网对战用Unet,如果是做网络对战用Photon实时服务器
4、用作临时处理HTTP协议的简单数据处理,HttpListener
5、简单存储数据:redis和mongodb
6、简单的让外网访问自己的html,用iis或者tomcat搭建站点
7、Tomcat另外一种轻量级服务器
总之,Bmob可以说是一种非常简单服务器,基本上可以满足个人调试开发。也可以在网络搜索其它Baas服务产品。
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:714次
排名:千里之外
原创:19篇
(8)(1)(13)(2)
(window.slotbydup = window.slotbydup || []).push({
id: '4740887',
container: s,
size: '250,250',
display: 'inlay-fix'android(50)
1.Bmob的回顾
&&& 大家好,我是张星,十一也快过去了,程序猿们是该收收心撸代码了;我们上个星期讲过),没看过的建议大伙去看看哦。相信大家对Bmob也有一定的了解,但是了解是远远 不够的,那么我今天就来给大家讲讲Bmob进阶系列把。
2.进阶篇的重点知识还原
1.配置问题
在Bmob的基础篇配置的基础上,仅仅加了一条配置:
useLibrary 'org.apache.http.legacy'
}如果在AS中编译出错的话,那还是老老实实的下载jar包复制到工程的libs目录下。
2.批量增加数据
* 批量增加数据
public void addDataMany(View v){
List&BmobObject& students = new ArrayList&BmobObject&();
for(int i=0;i&3;i++){
Student student = new Student();
student.setName(&zhangxing&+i);
students.add(student);
new BmobBatch().insertBatch(students).doBatch(new QueryListListener&BatchResult&() {
public void done(List&BatchResult& list, BmobException e) {
if(null == e){
for(int i=0 ; i&list.size(); i++){
BatchResult result = list.get(i);
BmobException b = result.getError();
if(null == b){
Toast.makeText(MainActivity.this,&第&+i+&个数据添加成功:&+result.getCreatedAt()+&,&
+result.getObjectId()+&,&
+result.getUpdatedAt() ,
Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,&第&+i+&个数据添加失败:&+b.getMessage()+&,&
+b.getErrorCode(),
Toast.LENGTH_SHORT).show();
Log.i(&bmob&,&失败:&+e.getMessage()+&,&+e.getErrorCode());
3.批量更新数据
* 更新数据
public void DataUpdateMany(View v){
List&BmobObject& students = new ArrayList&BmobObject&();
Student s1 = new Student();
s1.setObjectId(&fa675a528d&);
s1.setAge(23);
Student s2 = new Student();
s1.setObjectId(&fa675a528d&);
s1.setAge(24);
Student s3 = new Student();
s1.setObjectId(&03b15144b3&);
s1.setAge(25);
students.add(s1);
students.add(s2);
students.add(s3);
new BmobBatch().updateBatch(students).doBatch(new QueryListListener&BatchResult&() {
public void done(List&BatchResult& list, BmobException e) {
if(e==null){
for(int i=0;i&list.size();i++){
BatchResult result = list.get(i);
BmobException ex =result.getError();
if(ex==null){
Toast.makeText(MainActivity.this,&第&+i+&个数据批量更新成功:&+result.getUpdatedAt(),Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,&第&+i+&个数据批量更新失败:&+ex.getMessage()+&,&+ex.getErrorCode(),Toast.LENGTH_SHORT).show();
Log.i(&bmob&,&失败:&+e.getMessage()+&,&+e.getErrorCode());
4.批量删除数据
* 批量删除
public void deleteDataMany(View v){
List&BmobObject& students = new ArrayList&BmobObject&();
Student s1 = new Student();
s1.setObjectId(&fa675a528d&);
s1.setAge(23);
Student s2 = new Student();
s1.setObjectId(&fa675a528d&);
s1.setAge(24);
Student s3 = new Student();
s1.setObjectId(&03b15144b3&);
s1.setAge(25);
students.add(s1);
students.add(s2);
students.add(s3);
new BmobBatch().deleteBatch(students).doBatch(new QueryListListener&BatchResult&() {
public void done(List&BatchResult& list, BmobException e) {
if(e==null){
for(int i=0;i&list.size();i++){
BatchResult result = list.get(i);
BmobException ex =result.getError();
if(ex==null){
Toast.makeText(MainActivity.this,&第&+i+&个数据批量删除成功&,Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, &第&+i+&个数据批量删除失败:&+ex.getMessage()+&,&+ex.getErrorCode(), Toast.LENGTH_SHORT).show();
Log.i(&bmob&,&失败:&+e.getMessage()+&,&+e.getErrorCode());
5.用户注册时的邮箱验证
* 注册时邮箱验证
public void emailValidate(View v){
BmobUser bu = new BmobUser();
bu.setUsername(&zhangxing&);
bu.setPassword(&52077&);
bu.setEmail(&&);
//注意:不能用save方法进行注册
bu.signUp(new SaveListener&MyUser&() {
public void done(MyUser s, BmobException e) {
if(e == null){
Toast.makeText(MainActivity.this,&注册成功:& +s.toString(),Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,&注册失败:& +e.getMessage(),Toast.LENGTH_SHORT).show();
6.实时数据同步
* 实时数据同步,当数据发生变化时,程序监听到后立马把数据上传到Bmob SDK上,实现了实时数据同步的效果。
public void syncData(View v){
rtd.start(new ValueEventListener() {
public void onDataChange(JSONObject data) {
Log.d(&bmob&, &(&+data.optString(&action&)+&)&+&数据:&+data);
public void onConnectCompleted(Exception ex) {
Toast.makeText(MainActivity.this, &连接成功:&+rtd.isConnected(), Toast.LENGTH_SHORT).show();
if(rtd.isConnected()){
// 监听表更新
rtd.subTableDelete(&Student&);
7.获取附近的地理位置
* 获取地理位置
public void
hasLocation(View v){
BmobGeoPoint southwestOfSF = new BmobGeoPoint(111, 30);
BmobGeoPoint northeastOfSF = new BmobGeoPoint(116, 35);
BmobQuery&Student& query = new BmobQuery&Student&();
query.addWhereWithinGeoBox(&gspAdd&, southwestOfSF,northeastOfSF);
query.setLimit(10);
//获取最接近用户地点的10条数据
query.findObjects(new FindListener&Student&() {
public void done(List&Student& object,BmobException e) {
if(e==null){
Toast.makeText(MainActivity.this, &查询成功,共&+object.size()+&条数据&, Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, &查询失败:&+e.getMessage(), Toast.LENGTH_SHORT).show();
}实时数据同步十一个超炫的功能,当程序监听到数据改变时,数据会自动的同步到Bmob SDK,这种机制很适合游戏开发,比如典型的欢乐斗地主,一个人的出牌,其他的人马上就能获取到对方的出牌信息,所以,这项功能很酷。如果要学习的话,我这里有一个。
更多的功能在都有介绍,有兴趣的童阔以去学习哈,确实是一个不错的第三方平台,比人极力推荐没有错,哈哈。
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:99537次
积分:2340
积分:2340
排名:第17443名
原创:121篇
评论:52条
(2)(3)(10)(7)(13)(24)(6)(7)(1)(6)(12)(4)(16)(10)
(window.slotbydup = window.slotbydup || []).push({
id: '4740887',
container: s,
size: '250,250',
display: 'inlay-fix'iOS基于Bmob的实时通讯 - CSDN博客
iOS基于Bmob的实时通讯
最近刚完成一个基于Bmob后台的项目,用到了实时通讯这一功能,完成它还真是一个浩大的工程呐,一些步骤及重点在这里记录下来
下载安装BmobIMSDK
首先我们要通过官网下载最新的BmobIMSDK,将它导到自己的项目工程里面
引入相关的库文件
如果项目中已包含BmobSDK数据服务SDK的话,可以不添加新的框架,如果没有则需添加SystemConfiguration.framework、CoreFoundation.framework、Foundation.framework、CFNetwork.framwork、CoreGraphics.framework、sqlite3.tbd
在AppDelegate.m文件中,引入相关的头文件, 填入申请的授权Key(SDK使用的是应用密钥里的Application ID)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//初始化BmobSDK
[Bmob registerWithAppKey:@&Application ID&];
self.sharedIM = [BmobIM sharedBmobIM];
[self.sharedIM registerWithAppKey:@&Application ID&];
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightC
BmobUser *user = [BmobUser getCurrentUser];
//如果有用户了,不需要推送服务来推送消息的话,可以直接连接服务器
if (user) {
self.userId = user.objectId;
[self connectToServer];
//如果用户还未登录,则监听对应的通知,再进行处理
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLogin:) name:@&Login& object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLogout:) name:@&Logout& object:nil];
self.sharedIM.delegate =
return YES;
如果需要推送服务的话,可以在其相关代理那里设置调用 [self.sharedIM setupDeviceToken:@&xxxx&]的方法后,在连接服务器,当然需要在管理后台上传对应Bundle ID的p12文件,请勿加密
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(nonnull NSError *)error{
BmobUser *user = [BmobUser getCurrentUser];
if (user) {
[self connectToServer];
}-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
BmobUser *user = [BmobUser getCurrentUser];
if (user) {
//将deviceToken转成字符串
NSString *string = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding];
self.token = [[[string stringByReplacingOccurrencesOfString:@& & withString:@&&] stringByReplacingOccurrencesOfString:@&&& withString:@&&] stringByReplacingOccurrencesOfString:@&&& withString:@&&];
[self connectToServer];
}通知方法:
登陆对应处理
-(void)userLogin:(NSNotification *)noti{
NSString *userId = noti.
self.userId = userId;
[self connectToServer];
}退出登录的时候需要断开连接
-(void)userLogout:(NSNotification *)noti{
[self.sharedIM disconnect];
}连接服务器
-(void)connectToServer{
[self.sharedIM setupBelongId:self.userId];
[self.sharedIM setupDeviceToken:self.token];
[self.sharedIM connect];
}在应用进入前台或者后台的时候可以重新进行连接或者断开连接
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background t here you can undo many of the changes made on entering the background.
if (self.userId && self.userId.length & 0) {
[self connectToServer];
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
if ([self.sharedIM isConnected]) {
[self.sharedIM disconnect];
}需要说明的是,连接服务器建立一次即可,开发者自己控制连接服务器的时机。建立连接之前必须设置appKey和belongId,不然会抛出异常
可以在函数 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 添加推送的相关代码
CGFloat version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (version &= 10.0)
//iOS 10推送
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:UNAuthorizationOptionCarPlay | UNAuthorizationOptionSound | UNAuthorizationOptionBadge | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
NSLog(@& iOS 10 request notification success&);
NSLog(@& iOS 10 request notification fail&);
} else if (version &= 8.0) {
//iOS 8、9推送
UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc]init];
//注意:此处的Bundle ID要与你申请证书时填写的一致。
categorys.identifier=@&Bmob&;
UIUserNotificationSettings *userNotifiSetting = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:[NSSet setWithObjects:categorys,nil]];
[[UIApplication sharedApplication] registerUserNotificationSettings:userNotifiSetting];
[[UIApplication sharedApplication] registerForRemoteNotifications];
在初始化的部分,我们已经设置了self.sharedIM的delegate,我们只需要在对应的代理函数那里处理相关的应用逻辑即可。
在应用连接服务器的时候,SDK会主动的获取离线消息,并保存到本地数据库里面。在这里,开发者可能需要知道哪些人发来了消息,并且去下载相关人物信息。
-(void)didGetOfflineMessagesWithIM:(BmobIM *)im{
//获取哪些人的消息还未读
NSArray *objectIds = [self.sharedIM allConversationUsersIds];
if (objectIds && objectIds.count & 0) {
//查找服务器相关人物的信息
[UserService loadUsersWithUserIds:objectIds completion:^(NSArray *array, NSError *error) {
if (array && array.count & 0) {
//保存到本地数据库
[self.sharedIM saveUserInfos:array];
//发新用户的通知
[[NSNotificationCenter defaultCenter] postNotificationName:kNewMessageFromer object:nil];
}如果已经连接到服务器上了,就可以收到别人发送过来的消息,这是需要在另一个方法处理
-(void)didRecieveMessage:(BmobIMMessage *)message withIM:(BmobIM *)im{
//查看本地有无这个用户的信息
BmobIMUserInfo *userInfo = [self.sharedIM userInfoWithUserId:message.fromId];
if (!userInfo) {
//如果没有则去下载
[UserService loadUserWithUserId:message.fromId completion:^(BmobIMUserInfo *result, NSError *error) {
if (result) {
//保存到本地数据库
[self.sharedIM saveUserInfo:result];
//发新用户的通知
[[NSNotificationCenter defaultCenter] postNotificationName:kNewMessageFromer object:nil];
//发接收到新信息的通知
[[NSNotificationCenter defaultCenter] postNotificationName:kNewMessagesNotifacation object:message];
//发接收到新信息的通知
[[NSNotificationCenter defaultCenter] postNotificationName:kNewMessagesNotifacation object:message];
BmobUser *user = [[BmobUser alloc] init];
user.username = self.usernameTextField.
user.password = self.passwordTextField.
[user signUpInBackgroundWithBlock:^(BOOL isSuccessful, NSError *error) {
if (isSuccessful) {
[[NSNotificationCenter defaultCenter] postNotificationName:@&Login& object:user.objectId];
[self dismissViewControllerAnimated:YES completion:nil];
[self showInfomation:error.description];
[self showLoading];
[BmobUser loginWithUsernameInBackground:self.usernameTextField.text password:self.passwordTextField.text block:^(BmobUser *user, NSError *error) {
if (user) {
[self hideLoading];
[[NSNotificationCenter defaultCenter] postNotificationName:@&Login& object:user.objectId];
[self dismissViewControllerAnimated:YES completion:nil];
[self showInfomation:error.description];
获取好友列表
-(void)loadUserFriends{
[UserService friendsWithCompletion:^(NSArray *array, NSError *error) {
if (error) {
[self showInfomation:error.localizedDescription];
BmobUser *loginUser = [BmobUser getCurrentUser];
NSMutableArray *result
= [NSMutableArray array];
for (BmobObject *obj in array) {
BmobUser *friend =
if ([[(BmobUser *)[obj objectForKey:@&user&] objectId] isEqualToString:loginUser.objectId]) {
friend = [obj objectForKey:@&friendUser&];
friend = [obj objectForKey:@&user&];
BmobIMUserInfo *info = [BmobIMUserInfo userInfoWithBmobUser:friend];
[result addObject:info];
if (result && result.count & 0) {
[self.userArray setArray:result];
[self.tableView reloadData];
-(void)addFriend{
[UserService addFriendNoticeWithUserId:self.userInfo.userId completion:^(BOOL isSuccessful, NSError *error) {
if (error) {
[self showInfomation:error.localizedDescription];
[self showInfomation:@&已发送添加好友请求&];
通过IMSDK,用户可以与陌生人聊天,也可以与好友聊天,这个由我们控制。当需要发起聊天的时候,需要建立起一个BmobIMConversation对象来进行管理,SDK提供了方法来快速构建BmobIMConversation对象。
BmobIMConversation *conversation = [BmobIMConversation conversationWithId:self.userInfo.userId conversationType:BmobIMConversationTypeSingle];
conversation.conversationTitle = self.userInfo.//这是聊天对象名,显示到title上
查看聊天记录
加载第一页数据的时候,只需要将message设置为nil
-(void)loadMessageRecords{
NSArray *array = [self.conversation queryMessagesWithMessage:nil limit:10];//每次显示10条数据
if (array && array.count & 0) {
//根据消息更新时间进行排序
NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(BmobIMMessage *obj1, BmobIMMessage *obj2) {
if (obj1.updatedTime & obj2.updatedTime) {
return NSOrderedD
}else if(obj1.updatedTime &
obj2.updatedTime) {
return NSOrderedA
return NSOrderedS
[self.messagesArray setArray:result];
[self.tableView reloadData];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messagesArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}加载之前的历史消息记录,可以通过将message参数设置为时间为最后一条消息即可
-(void)loadMoreRecords{
if (!self.finished) {
self.page ++;
[self.freshControl beginRefreshing];
if (self.messagesArray.count &= 0) {
[self.freshControl endRefreshing];
BmobIMMessage *msg = [self.messagesArray firstObject];
NSArray *array = [self.conversation queryMessagesWithMessage:msg limit:10];
if (array && array.count & 0) {
NSMutableArray *messages = [NSMutableArray arrayWithArray:self.messagesArray];
[messages addObjectsFromArray:array];
NSArray *result = [messages sortedArrayUsingComparator:^NSComparisonResult(BmobIMMessage *obj1, BmobIMMessage *obj2) {
if (obj1.updatedTime & obj2.updatedTime) {
return NSOrderedD
}else if(obj1.updatedTime &
obj2.updatedTime) {
return NSOrderedA
return NSOrderedS
[self.messagesArray setArray:result];
[self.tableView reloadData];
self.finished = YES;
[self showInfomation:@&没有更多的历史消息&];
[self showInfomation:@&没有更多的历史消息&];
[self.freshControl endRefreshing];
发送文本消息
-(void)sendTextWithTextField:(UITextField *)textField{
if (textField.text.length == 0) {
[self showInfomation:@&请输入内容&];
//创建BmobIMTextMessage对象
BmobIMTextMessage *message = [BmobIMTextMessage messageWithText:textField.text attributes:nil];
//聊天类型设置为单聊
message.conversationType =
BmobIMConversationTypeS
message.createdTime = (uint64_t)([[NSDate date] timeIntervalSince1970] * 1000);
message.updatedTime = message.createdT
[self.messagesArray addObject:message];
[self.tableView reloadData];
self.bottomView.textField.text =
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messagesArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
__weak typeof(self)weakSelf =
[self.conversation sendMessage:message completion:^(BOOL isSuccessful, NSError *error) {
[weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.messagesArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
发送图片消息的流程是通过把拍照或者图片的内容,转成Data,然后通过Bmob文件上传接口来上传文件,获取到相关的信息(文件地址之类的),再构造对应的BmobIMImageMessage对象来发送消息。
这里封装一个直接传入image就能发送图片的方法
+(void)uploadImage:(UIImage *)image
completion:(uploadBlock)block
progress:(BmobProgressBlock)progressBlock
BmobFile *file = [[BmobFile alloc] initWithFileName:[NSString stringWithFormat:@&%.0f.png&,[[NSDate date] timeIntervalSinceReferenceDate] ] withFileData:UIImagePNGRepresentation(image)];
[file saveInBackgroundByDataSharding:^(BOOL isSuccessful, NSError *error) {
BmobIMImageMessage *message =
if (!error) {
message = [BmobIMImageMessage messageWithUrl:file.url attributes:@{KEY_METADATA:@{KEY_HEIGHT:@(image.size.height),KEY_WIDTH:@(image.size.width)}}];
message.conversationType = BmobIMConversationTypeS
message.createdTime = (uint64_t)([[NSDate date] timeIntervalSince1970] * 1000);
message.updatedTime = message.createdT
if (block) {
block(message,error);
} progressBlock:^(CGFloat progress) {
if (progressBlock) {
progressBlock(progress);
然后可以直接调用方法来发送图片,并在当前页显示出来
[MessageService uploadImage:resizeImage completion:^(BmobIMImageMessage *message, NSError *error) {
if (!error) {
[self.messagesArray addObject:message];
[self scrollToBottom];
__weak typeof(self)weakSelf =
[self.conversation sendMessage:message completion:^(BOOL isSuccessful, NSError *error) {
[weakSelf reloadLastRow];
[self showInfomation:error.localizedDescription];
} progress:^(CGFloat progress) {
[self showProgress:progress];
}];发送语音文件(模拟器上不能发送语音,只有真机上才可以操作,还需要设置访问录音的白名单)
发送语音消息的流程是把录音下载的Data转成AMR格式,保存在本地,然后通过Bmob文件上传接口来上传文件,获取到相关的信息(文件地址之类的),再构造对应的BmobIMAudioMessage对象来发送消息。
封装一个直接传入NSData就能发送语音文件的方法
+(void)uploadAudio:(NSData *)data
duration:(CGFloat)duration
completion:(uploadBlock)block
progress:(BmobProgressBlock)progressBlock
//保存在本地
NSString *filename = [NSString stringWithFormat:@&%.0f.amr&,[NSDate timeIntervalSinceReferenceDate]];
NSString *path = [[CommonUtil audioCacheDirectory] stringByAppendingPathComponent:filename];
[data writeToFile:path options:NSDataWritingAtomic error:nil];
BmobFile *file = [[BmobFile alloc] initWithFileName:filename withFileData:data];
[file saveInBackground:^(BOOL isSuccessful, NSError *error) {
BmobIMAudioMessage *message =
if (!error) {
message = [BmobIMAudioMessage messageWithUrl:file.url attributes:@{KEY_METADATA:@{KEY_DURATION:@(duration)}}];
message.conversationType = BmobIMConversationTypeS
message.createdTime = (uint64_t)([[NSDate date] timeIntervalSince1970] * 1000);
message.updatedTime = message.createdT
message.localPath
= [path stringByReplacingOccurrencesOfString:NSHomeDirectory() withString:@&&];
if (block) {
block(message,error);
} withProgressBlock:^(CGFloat progress) {
if (progressBlock) {
progressBlock(progress);
}直接调用这个方法就能发送语音文件
[MessageService uploadAudio:data
duration:duration
completion:^(BmobIMAudioMessage *message, NSError *error) {
if (!error) {
[self.messagesArray addObject:message];
[self scrollToBottom];
__weak typeof(self)weakSelf =
[self.conversation sendMessage:message completion:^(BOOL isSuccessful, NSError *error) {
[weakSelf reloadLastRow];
} progress:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessage:) name:kNewMessagesNotifacation object:nil];-(void)receiveMessage:(NSNotification *)noti{
BmobIMMessage *message = noti.
//如果是消息来源是当前聊天用户,就将其加载到内存里并显示出来
if ([message.fromId isEqualToString:self.conversation.conversationId]) {
[self.messagesArray addObject:message];
[self.tableView reloadData];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messagesArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}在这里的描述不是特别详细,因为这是一个特别大的模块,所以一些小的细节并没有展示出来,以及运用tableview来展示聊天的排版,通过自己与好友的id区分左右排版,通过id获得用户的信息展示,项目中的截图:
本文已收录于以下专栏:
相关文章推荐
iOS之实时通讯socket
我的上一篇博客简要的介绍了一下我对即时通讯的一些尝试,后面还介绍了通过bmob实现即时通讯的方式,上一篇主要是对我的一些经验的分享,所以我只提取了很简要的部分讲解,考虑到一些读者可能难以理解,所以为帮...
bmob是一个后端提供商,为用户提供
支持丰富的数据类型,灵活方便的增删改查,可视化的数据操作,安全的角色和ACL管理,多表关联处理,数据的批量处理,本地数据缓存,开发者们无需关注服...
关键词 RTSS Win32 UART NI SharedMemory
在工控领域,特别是我比较熟悉的半导体行业,设备与设备之间的通讯一般有TTL, RS232, GPIB, RJ45等,RS232...
最近因为学弟项目需求 要做实时通讯,想让我研究研究,我就帮忙写了写,怎么说呢,收获也是有的吧,然后打算把整个通讯给大家展示一遍,包括服务端和客户端,有兴趣的可以关注小编
源码下载地址:http://...
这是微软官方SignalR 2.0教程Getting Started with ASP.NET
SignalR 2.0系列的翻译,这里是第七篇:SignalR的高频实时通讯
原文:Tutor...
socket通信的原理在这里就不说了,它的用途还是比较广泛的,我们可以使用socket来做一个API接口出来,也可以使用socket来实现两个程序之间的通信,我们来研究一下在php里面如何实现sock...
via:AVOS Cloud Blog
很多开发者想在自己的 App 中添加实时通讯的功能,但通常因为没有合适的后端支持,最终没能实现。而 AVOSCloud 与时俱进,给大家带来了希望。下面就来介...
他的最新文章
讲师:宋宝华
讲师:何宇健
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)

我要回帖

更多关于 实时系统能做到硬实时 的文章

 

随机推荐