下载iOS_Demo

点击这里下载demo(iOS)源码

Bmob即时聊天demo包含了一个完整的即时通讯的App,功能包括:

  1. 支持好友管理功能,包括添加好友、删除好友、获取好友列表,也可以与你已有的用户系统完全解耦;
  2. 支持的消息类型:纯文本,语音,图片,自定义消息
  3. 支持会话的本地化存储;

iOS界面效果

iOS联系人页面

IM服务 iOS SDK开发文档 - 图1

iOS会话页面

IM服务 iOS SDK开发文档 - 图2

iOS聊天页面

IM服务 iOS SDK开发文档 - 图3

iOS搜索联系人页面

IM服务 iOS SDK开发文档 - 图4

iOS设置页面

IM服务 iOS SDK开发文档 - 图5

iOSIM快速入门

下载安装BmobIMSDK

  1. 通过官网下载新的BmobIMSDK
  2. 新建项目将BmobIMSDK 复制到新的项目工程
  3. 具体可以参照Demo

配置相关服务

如果需要用到推送服务,所以需要在管理后台上传对应Bundle ID的p12文件,请勿加密,
详细详细请参照:http://docs.bmob.cn/iospush/index.html?menukey=otherdoc&key=iospush

引入相关的库文件

如果项目中已包含BmobSDK数据服务SDK的话,可以不添加新的框架,如果没有则需添加SystemConfiguration.framework、CoreFoundation.framework、Foundation.framework、CFNetwork.framwork、CoreGraphics.framework、sqlite3.tbd

初始化

在你的XCode工程中的AppDelegate.m文件中,引入相关的头文件, 填入申请的授权Key(SDK使用的是应用密钥里的Application ID),示例如下:

#import <BmobIMSDK/BmobIMSDK.h>

  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  2. // Override point for customization after application launch.
  3. //这里使用的是BmobSDK提供的用户系统,所以需要初始化BmobSDK
  4. [Bmob registerWithAppKey:@"Application ID"];
  5. self.sharedIM = [BmobIM sharedBmobIM];
  6. [self.sharedIM registerWithAppKey:@"Application ID"];
  7. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
  8. BmobUser *user = [BmobUser getCurrentUser];
  9. //如果有用户了,不需要推送服务来推送消息的话,可以直接连接服务器
  10. if (user) {
  11. self.userId = user.objectId;
  12. [self connectToServer];
  13. }else{
  14. //如果用户还未登录,则监听对应的通知,再进行处理
  15. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLogin:) name:@"Login" object:nil];
  16. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLogout:) name:@"Logout" object:nil];
  17. }
  18. self.sharedIM.delegate = self;
  19. return YES;
  20. }

如果需要推送服务的话,可以在其相关代理那里设置调用 [self.sharedIM setupDeviceToken:@”xxxx”]的方法后,在连接服务器

  1. -(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(nonnull NSError *)error{
  2. BmobUser *user = [BmobUser getCurrentUser];
  3. if (user) {
  4. [self connectToServer];
  5. }
  6. }
  1. -(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
  2. BmobUser *user = [BmobUser getCurrentUser];
  3. if (user) {
  4. //开发者自己将deviceToken转成字符串
  5. NSString *string = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding];
  6. self.token = [[[string stringByReplacingOccurrencesOfString:@" " withString:@""] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""];
  7. [self connectToServer];
  8. }
  9. }

登录的对应处理是

  1. -(void)userLogin:(NSNotification *)noti{
  2. NSString *userId = noti.object;
  3. self.userId = userId;
  4. [self connectToServer];
  5. }

退出登录的时候需要断开连接

  1. -(void)userLogout:(NSNotification *)noti{
  2. [self.sharedIM disconnect];
  3. }

连接服务器

  1. -(void)connectToServer{
  2. [self.sharedIM setupBelongId:self.userId];
  3. [self.sharedIM setupDeviceToken:self.token];
  4. [self.sharedIM connect];
  5. }

在应用进入前台或者后台的时候可以重新进行连接或者断开连接

进入前台

  1. - (void)applicationWillEnterForeground:(UIApplication *)application {
  2. // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
  3. if (self.userId && self.userId.length > 0) {
  4. [self connectToServer];
  5. }
  6. }

进入后台

  1. - (void)applicationDidEnterBackground:(UIApplication *)application {
  2. // 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.
  3. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  4. if ([self.sharedIM isConnected]) {
  5. [self.sharedIM disconnect];
  6. }

需要说明的是,连接服务器建立一次即可,开发者自己控制连接服务器的时机。建立连接之前必须设置appKey和belongId,不然会抛出异常

注册推送

可以在函数 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 添加推送的相关代码

  1. if (IS_iOS8) {
  2. //iOS8推送
  3. UIMutableUserNotificationCategory*categorys = [[UIMutableUserNotificationCategory alloc]init];
  4. categorys.identifier=@"BmobIMDemo";
  5. UIUserNotificationSettings*userNotifiSetting = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound)
  6. categories:[NSSet setWithObjects:categorys,nil]];
  7. [[UIApplication sharedApplication]registerUserNotificationSettings:userNotifiSetting];
  8. [[UIApplication sharedApplication]registerForRemoteNotifications];
  9. }else{
  10. [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
  11. }

接收消息

在初始化的部分,我们已经设置了self.sharedIM的delegate,我们只需要在对应的代理函数那里处理相关的应用逻辑即可。
在应用连接服务器的时候,SDK会主动的获取离线消息,并保存到本地数据库里面。在这里,开发者可能需要知道哪些人发来了消息,并且去下载相关人物信息。

  1. -(void)didGetOfflineMessagesWithIM:(BmobIM *)im{
  2. //获取哪些人的消息还未读
  3. NSArray *objectIds = [self.sharedIM allConversationUsersIds];
  4. if (objectIds && objectIds.count > 0) {
  5. //Demo里面的方法去查找服务器相关人物的信息
  6. [UserService loadUsersWithUserIds:objectIds completion:^(NSArray *array, NSError *error) {
  7. if (array && array.count > 0) {
  8. //保存到本地数据库
  9. [self.sharedIM saveUserInfos:array];
  10. //发新用户的通知
  11. [[NSNotificationCenter defaultCenter] postNotificationName:kNewMessageFromer object:nil];
  12. }
  13. }];
  14. }
  15. }

另一方面,已经连接到服务器上了,就可以收到别人发送过来的消息,这是需要在另一个方法处理

  1. -(void)didRecieveMessage:(BmobIMMessage *)message withIM:(BmobIM *)im{
  2. //查看本地有无这个用户的信息
  3. BmobIMUserInfo *userInfo = [self.sharedIM userInfoWithUserId:message.fromId];
  4. if (!userInfo) {
  5. //如果没有则去下载
  6. [UserService loadUserWithUserId:message.fromId completion:^(BmobIMUserInfo *result, NSError *error) {
  7. if (result) {
  8. //保存到本地数据库
  9. [self.sharedIM saveUserInfo:result];
  10. //发新用户的通知
  11. [[NSNotificationCenter defaultCenter] postNotificationName:kNewMessageFromer object:nil];
  12. }
  13. //发接收到新信息的通知
  14. [[NSNotificationCenter defaultCenter] postNotificationName:kNewMessagesNotifacation object:message];
  15. }];
  16. }else{
  17. //发接收到新信息的通知
  18. [[NSNotificationCenter defaultCenter] postNotificationName:kNewMessagesNotifacation object:message];
  19. }
  20. }

用户管理

注册

当用户还未进行注册的时候可以通过调用方法来进行简单的注册

  1. BmobUser *user = [[BmobUser alloc] init];
  2. user.username = self.usernameTextField.text;
  3. user.password = self.passwordTextField.text;
  4. [user signUpInBackgroundWithBlock:^(BOOL isSuccessful, NSError *error) {
  5. if (isSuccessful) {
  6. [[NSNotificationCenter defaultCenter] postNotificationName:@"Login" object:user.objectId];
  7. [self dismissViewControllerAnimated:YES completion:nil];
  8. }else{
  9. [self showInfomation:error.description];
  10. }
  11. }];

登录

用户已经注册了,想要在此应用登录的话,可以直接调用登录的方法

  1. [self showLoading];
  2. [BmobUser loginWithUsernameInBackground:self.usernameTextField.text password:self.passwordTextField.text block:^(BmobUser *user, NSError *error) {
  3. if (user) {
  4. [self hideLoading];
  5. [[NSNotificationCenter defaultCenter] postNotificationName:@"Login" object:user.objectId];
  6. [self dismissViewControllerAnimated:YES completion:nil];
  7. }else{
  8. [self showInfomation:error.description];
  9. }
  10. }];

获取好友列表

  1. -(void)loadUserFriends{
  2. [UserService friendsWithCompletion:^(NSArray *array, NSError *error) {
  3. if (error) {
  4. [self showInfomation:error.localizedDescription];
  5. }else{
  6. BmobUser *loginUser = [BmobUser getCurrentUser];
  7. NSMutableArray *result = [NSMutableArray array];
  8. for (BmobObject *obj in array) {
  9. BmobUser *friend = nil;
  10. if ([[(BmobUser *)[obj objectForKey:@"user"] objectId] isEqualToString:loginUser.objectId]) {
  11. friend = [obj objectForKey:@"friendUser"];
  12. }else{
  13. friend = [obj objectForKey:@"user"];
  14. }
  15. BmobIMUserInfo *info = [BmobIMUserInfo userInfoWithBmobUser:friend];
  16. [result addObject:info];
  17. }
  18. if (result && result.count > 0) {
  19. [self.userArray setArray:result];
  20. [self.tableView reloadData];
  21. }
  22. }
  23. }];
  24. }

添加好友

  1. -(void)addFriend{
  2. [UserService addFriendNoticeWithUserId:self.userInfo.userId completion:^(BOOL isSuccessful, NSError *error) {
  3. if (error) {
  4. [self showInfomation:error.localizedDescription];
  5. }else{
  6. [self showInfomation:@"已发送添加好友请求"];
  7. }
  8. }];
  9. }

消息发送

通过IMSDK,用户可以与陌生人聊天,也可以与好友聊天,这个由开发者自由控制。当需要发起聊天的时候,需要建立起一个BmobIMConversation对象来进行管理,SDK提供了方法来快速构建BmobIMConversation对象。

  1. //
  2. BmobIMConversation *conversation = [BmobIMConversation conversationWithId:self.userInfo.userId conversationType:BmobIMConversationTypeSingle];
  3. conversation.conversationTitle = self.userInfo.name;

查看聊天记录

进入聊天页面是,开发者可能需要让用户查看最近的聊天记录,这个时候可以通过BmobIMConversation 类提供的

-(NSArray *)queryMessagesWithMessage:(BmobIMMessage *)message limit:(int)limit;来处理这个需求。

例如,加载第一页数据的时候,只需要将message设置为nil,即可获取到

  1. -(void)loadMessageRecords{
  2. NSArray *array = [self.conversation queryMessagesWithMessage:nil limit:10];
  3. if (array && array.count > 0) {
  4. //排序
  5. NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(BmobIMMessage *obj1, BmobIMMessage *obj2) {
  6. if (obj1.updatedTime > obj2.updatedTime) {
  7. return NSOrderedDescending;
  8. }else if(obj1.updatedTime < obj2.updatedTime) {
  9. return NSOrderedAscending;
  10. }else{
  11. return NSOrderedSame;
  12. }
  13. }];
  14. [self.messagesArray setArray:result];
  15. [self.tableView reloadData];
  16. [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messagesArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
  17. }
  18. }

加载之前的历史消息记录,可以通过将message参数设置为时间为最后一条消息即可

  1. -(void)loadMoreRecords{
  2. if (!self.finished) {
  3. self.page ++;
  4. [self.freshControl beginRefreshing];
  5. if (self.messagesArray.count <= 0) {
  6. [self.freshControl endRefreshing];
  7. return;
  8. }
  9. BmobIMMessage *msg = [self.messagesArray firstObject];
  10. NSArray *array = [self.conversation queryMessagesWithMessage:msg limit:10];
  11. if (array && array.count > 0) {
  12. NSMutableArray *messages = [NSMutableArray arrayWithArray:self.messagesArray];
  13. [messages addObjectsFromArray:array];
  14. //排序
  15. NSArray *result = [messages sortedArrayUsingComparator:^NSComparisonResult(BmobIMMessage *obj1, BmobIMMessage *obj2) {
  16. if (obj1.updatedTime > obj2.updatedTime) {
  17. return NSOrderedDescending;
  18. }else if(obj1.updatedTime < obj2.updatedTime) {
  19. return NSOrderedAscending;
  20. }else{
  21. return NSOrderedSame;
  22. }
  23. }];
  24. [self.messagesArray setArray:result];
  25. [self.tableView reloadData];
  26. }else{
  27. self.finished = YES;
  28. [self showInfomation:@"没有更多的历史消息"];
  29. }
  30. }else{
  31. [self showInfomation:@"没有更多的历史消息"];
  32. }
  33. [self.freshControl endRefreshing];
  34. }

发送消息

发送文本消息

  1. -(void)sendTextWithTextField:(UITextField *)textField{
  2. if (textField.text.length == 0) {
  3. [self showInfomation:@"请输入内容"];
  4. }else{
  5. //创建BmobIMTextMessage对象
  6. BmobIMTextMessage *message = [BmobIMTextMessage messageWithText:textField.text attributes:nil];
  7. //聊天类型设置为单聊
  8. message.conversationType = BmobIMConversationTypeSingle;
  9. message.createdTime = (uint64_t)([[NSDate date] timeIntervalSince1970] * 1000);
  10. message.updatedTime = message.createdTime;
  11. [self.messagesArray addObject:message];
  12. [self.tableView reloadData];
  13. self.bottomView.textField.text = nil;
  14. [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messagesArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
  15. __weak typeof(self)weakSelf = self;
  16. [self.conversation sendMessage:message completion:^(BOOL isSuccessful, NSError *error) {
  17. [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.messagesArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
  18. }];
  19. }
  20. }

发送图片

发送图片消息的流程是通过把拍照或者图片的内容,转成Data,然后通过Bmob文件上传接口来上传文件,获取到相关的信息(文件地址之类的),再构造对应的BmobIMImageMessage对象来发送消息。

Demo封装了一个直接传入image就能发送图片的方法

  1. +(void)uploadImage:(UIImage *)image
  2. completion:(uploadBlock)block
  3. progress:(BmobProgressBlock)progressBlock;

然后可以直接调用方法来发送图片,并在当前页显示出来

  1. [MessageService uploadImage:resizeImage completion:^(BmobIMImageMessage *message, NSError *error) {
  2. if (!error) {
  3. [self.messagesArray addObject:message];
  4. [self scrollToBottom];
  5. __weak typeof(self)weakSelf = self;
  6. [self.conversation sendMessage:message completion:^(BOOL isSuccessful, NSError *error) {
  7. [weakSelf reloadLastRow];
  8. }];
  9. }else{
  10. [self showInfomation:error.localizedDescription];
  11. }
  12. } progress:^(CGFloat progress) {
  13. [self showProgress:progress];
  14. }];

发送语音文件

发送语音消息的流程是把录音下载的Data转成AMR格式,保存在本地,然后通过Bmob文件上传接口来上传文件,获取到相关的信息(文件地址之类的),再构造对应的BmobIMAudioMessage对象来发送消息。

Demo封装了一个直接传入NSData就能发送语音文件的方法

  1. +(void)uploadAudio:(NSData *)data
  2. duration:(CGFloat)duration
  3. completion:(uploadBlock)block
  4. progress:(BmobProgressBlock)progressBlock

直接调用这个方法就能发送语音文件

  1. [MessageService uploadAudio:data
  2. duration:duration
  3. completion:^(BmobIMAudioMessage *message, NSError *error) {
  4. if (!error) {
  5. [self.messagesArray addObject:message];
  6. [self scrollToBottom];
  7. __weak typeof(self)weakSelf = self;
  8. [self.conversation sendMessage:message completion:^(BOOL isSuccessful, NSError *error) {
  9. [weakSelf reloadLastRow];
  10. }];
  11. }
  12. } progress:nil];

发送其他文件消息

当开发者需要发送其他类型的文件消息的时候,先要继承BmobIMFileMessage类,通过BmobSDK提供的文件上传接口,把文件上传至服务器上,获取到url,再去创建对应的对象。
这里的流程可以参照发送图片,发送语音的相关源代码。当然了,开发者也必须指定其msgType属性,好让应用可以根据这个属性来显示相应的视图。

发送位置

  1. BmobIMLocationMessage *message = [BmobIMLocationMessage messageWithAddress:@"广州大学城" attributes:@{KEY_METADATA:@{KEY_LATITUDE:@(23.039),KEY_LONGITUDE:@(113.388)}}];
  2. message.conversationType = BmobIMConversationTypeSingle;
  3. message.createdTime = (uint64_t)([[NSDate date] timeIntervalSince1970] * 1000);
  4. message.updatedTime = message.createdTime;
  5. [self.messagesArray addObject:message];
  6. [self scrollToBottom];
  7. __weak typeof(self)weakSelf = self;
  8. [self.conversation sendMessage:message completion:^(BOOL isSuccessful, NSError *error) {
  9. [weakSelf reloadLastRow];
  10. }];

发送自定义消息

开发者也可以发送自定义消息(需继承BmobIMMessage),例如添加好友的请求,当前聊天对象正在输入之类的消息,这种暂态的消息是不需要存储在数据库的,需要设置extra{KEY_IS_TRANSIENT:@(YES),…}。其他额外信息开发者可以自由设置

例如发送添加好友通知,这种消息是暂时的,不需要保存到数据库里面,可以这样构造

  1. BmobIMMessage *message = [[BmobIMMessage alloc] init];
  2. message.msgType = @"notice";
  3. message.conversationType = BmobIMConversationTypeSingle;
  4. message.extra = @{KEY_IS_TRANSIENT:@(YES)};
  5. message.content = @"添加好友";
  6. [self.conversation sendMessage:message completion:^(BOOL isSuccessful, NSError *error) {
  7. NSLog(@"error %@",error.localizedDescription);
  8. }];

接收消息

在上一个大章节 接收消息 那里,我们已经把接收到的消息用通知的形式广播出来,我们只需要在聊天页面添加观察者来监听通知就行了。
在Demo里在函数- (void)viewDidLoad

  1. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessage:) name:kNewMessagesNotifacation object:nil];

-(void)receiveMessage:(NSNotification *)noti进行对应的处理

  1. -(void)receiveMessage:(NSNotification *)noti{
  2. BmobIMMessage *message = noti.object;
  3. //如果是消息来源是当前聊天用户,就将其加载到内存里并显示出来
  4. if ([message.fromId isEqualToString:self.conversation.conversationId]) {
  5. [self.messagesArray addObject:message];
  6. [self.tableView reloadData];
  7. [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messagesArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
  8. }
  9. }