澳门威利斯人_威利斯人娱乐「手机版」

来自 办公软件 2020-04-01 23:39 的文章
当前位置: 澳门威利斯人 > 办公软件 > 正文

集成环信的即时通讯,发送文本消息

����```

上官方网址注册账号

聊天调节器(ChatViewControllerState of Qatar分界面搭建

/*1.潜藏和突显tabBar2.为inputView 加分界线3.title 密友闲聊标题4.监听键盘弹出 对相应的布局做改善5.得到发送新闻音信*/

先是来到环信的官网,然后登入.未有账号先注册一个.

14.闲谈分界面-工具条制版

// 宏 自定义View高度为44

跻身现在成立应用,如图

1卡塔尔(قطر‎搭建分界面

@interface bingeChatViewController () <UITableViewDelegate,UITableViewDataSource, UITextFieldDelegate>

图片 1

充裕闲谈调整器:到mainstoryboard中找到addressbook的tableview调整器,将cell拖线给一个uiviewcontroller选择show,在该调节器导航栏中间拖一个navigationitem,改正名字为“谈天界面”,拖二个uiew尺寸与底部tabar相仿大小,并隐瞒头部的tabar(1.点击调控器bottombar选拔为none.2.点击调节器勾选Hide Bottom Bar

//由这七个控件组成@property (nonatomic,strong卡塔尔国 UITableView *tableView;@property (nonatomic,strong) bingeInputView *inputView;

开创应用分界面

on PushState of Qatar。(注意输入框为textview),中间有个别拖三个tableview,自动布局,设置代理,注意tableview中有个天性,拖动时掩瞒键盘(scrollview-keyboard-采用dissmiss on drag)

// 发送消息列表数组@property (nonatomic,strong卡塔尔 NSMutableArray *chatMsgs;

点击分明后,来到这一个分界面,只须要牢牢记住应用标示(应用软件KeyState of Qatar就可以,待会儿会在代码里使用它.

自定义该闲聊调整器:chatviewcontroller,将storyboard中决定器class改为该调控器的类名。

@end

图片 2

2卡塔尔国达成键盘退出、弹出,工具栏紧链接成效:调控器代码如下:

@implementation bingeChatViewController// 1.-(UITableView *)tableView {if (!_tableView) {_tableView = [[UITableView alloc]init];// 代理方法_tableView.dataSource = self;_tableView.delegate = self;// Xib View 的位置_tableView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - KInputViewH);}return _tableView;}

显示屏快速照相 2015-01-04 上午7.18.38.png

//1.将工具条尾部的牢笼拖线为该调节器的品质。

// 2.-inputView {if (!_inputView) {_inputView = [bingeInputView binge_inputView];_inputView.textField.delegate = self;_inputView.frame = CGRectMake(0, self.view.bounds.size.height - KInputViewH, self.view.bounds.size.width, KInputViewH);}return _inputView;}

下一场用cocoapods导入环信SDK,我们能够因此那篇博客来安装cocoapods.

@property(weak,nonatomic)IBOutletNSLayoutConstraint*chatInputBottomConstant;

  • (NSMutableArray *)chatMsgs {if (!_chatMsgs) {_chatMsgs = [NSMutableArray array];}return _chatMsgs;}

创办项目

//2.viewdidload中监听键盘弹出/回方法

// 3.

开垦终端,输入cd,然后将项目入进去回车,就跳到花色地址,输入指令:pod

//1State of Qatar.监听键盘弹出,把inputToolbar(输入工具条State of Qatar往上移

  • viewDidLoad {[super viewDidLoad];// 加多子控件[self.view addSubview:self.tableView];[self.view addSubview:self.inputView];// 加多标题self.title = self.buddy.username;

init,然后会转移三个Podfile,双击这些文件,将当中的东西全删了,然后输入:pod 'EaseMobSDK',然后在极端输入指令:pod

[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(kbWillShow:)name:UIKeyboardWillShowNotificationobject:nil];

install(如若不行可以尝试:pod install --verbose

//2卡塔尔国.监听键盘退出,inputToolbar恢复生机原位

// 点击空白处收键盘UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];[self.view addGestureRecognizer:singleTap];// 获取会话中的聊天记录[self binge_reloadChatMsgs];//监听键盘弹出 对相应的布局组修改[self binge_observerKeyboardFrameChange];

--no-repo-update卡塔尔国.接下来就等着SDK下载安装到花色里了,大致几分钟后就好了.此时要求双击.xcworkspace的至极文件进去.SDK集成就达成了(不知情为啥官方文档里面写的购并极其复杂,须要导入各个框架,修正比超级多事物,其实如若终端一条指令就OK了卡塔尔(قطر‎.

[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(kbWillHide:)name:UIKeyboardWillHideNotificationobject:nil];

}

AppDelegate

//3.得以完结监听方法

  • viewWillAppear:animated {[super viewWillAppear:animated];// 隐藏 tabBar 控件self.navigationController.tabBarController.tabBar.hidden = YES;}
  • viewWillDisappear:animated {[super viewWillDisappear:animated];// 隐藏 tabBar 控件self.navigationController.tabBarController.tabBar.hidden = NO;}

世家还记得刚才的电脑软件Key吧,在AppDelegate里面供给登记使用.

#pragma mark键盘展现时会触发的办法

#import"AppDelegate.h"#import"ViewController.h"#import@interfaceAppDelegate()@end@implementationAppDelegate- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {    _window = [[UIWindowalloc]initWithFrame:[UIScreenmainScreen].bounds];    _window.backgroundColor = [UIColorwhiteColor];    [_window makeKeyAndVisible];UINavigationController*nav = [[UINavigationControlleralloc]initWithRootViewController:[[ViewController alloc]init]];    _window.rootViewController = nav;//注册环信[[EaseMob sharedInstance]registerSDKWithAppKey:@"xmh123#cdxmh"apnsCertName:@""];returnYES;}- (void)applicationWillResignActive:(UIApplication*)application {// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.}- (void)applicationDidEnterBackground:(UIApplication*)application {    [[EaseMob sharedInstance] applicationDidEnterBackground:application];}- (void)applicationWillEnterForeground:(UIApplication*)application {    [[EaseMob sharedInstance] applicationWillEnterForeground:application];}- (void)applicationDidBecomeActive:(UIApplication*)application {// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.}- (void)applicationWillTerminate:(UIApplication*)application {    [[EaseMob sharedInstance]applicationWillTerminate:application];}@end

-(void)kbWillShow:(NSNotification*)noti{

  • (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.chatMsgs.count;}

登入分界面

//1.到手键盘高度

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

图片 3

//1.1得到键盘甘休时候的地点

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"chatID"];if  { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"chatID"]; EMMessage *msg = self.chatMsgs[indexPath.row]; NSLog(@"msg = %@",msg); EMTextMessageBody *body = msg.messageBodies.firstObject; cell.textLabel.text = body.text;}return cell; // 创建消息后 记得返回到cell

登录分界面

CGRectkbEndFrm = [noti.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];

}

拜见那部分的代码吧.

CGFloatkbHeight = kbEndFrm.size.height;

// 滑动空白处隐瞒键盘

#import"ViewController.h"#import"RegisterViewController.h"#import"FriendListViewController.h"#import@interfaceViewController()@property(nonatomic,strong)UITextField*userNameTextField;//用户名@property(nonatomic,strong)UITextField*passwordTextField;//密码@property(nonatomic,strong)UIButton*loginButton;//登入开关@property(nonatomic,strong卡塔尔国UIButton*registerButton;//注册按键@end@implementationViewController- (void卡塔尔(قطر‎viewDidLoad {    [superviewDidLoad];self.view.backgroundColor = [UIColorwhiteColor];self.navigationController.navigationBar.translucent =NO;self.title =@"登入分界面";UILabel*usernameLabel = [[UILabelalloc]initWithFrame:CGRectMake(20,100,80,50)];    usernameLabel.text =@"用户名";    usernameLabel.font = [UIFontsystemFontOfSize:25];    [self.view addSubview:usernameLabel];    _userNameTextField = [[UITextFieldalloc]initWithFrame:CGRectMake(usernameLabel.frame.origin.x

//2.改进inputToolbar底部封锁

  • scrollViewWillBeginDragging:(UIScrollView *)scrollView {

    [self.view endEditing:YES];}

  • usernameLabel.frame.size.width 10, usernameLabel.frame.origin.y,250,50)];    _userNameTextField.borderStyle =3;    _userNameTextField.placeholder =@"请输入顾客名";    [self.view addSubview:_userNameTextField];UILabel*passwordLabel = [[UILabelalloc]initWithFrame:CGRectMake(usernameLabel.frame.origin.x, usernameLabel.frame.origin.y usernameLabel.frame.size.height 10, usernameLabel.frame.size.width, usernameLabel.frame.size.height)];    passwordLabel.text =@"密码";    passwordLabel.font = [UIFontsystemFontOfSize:25];    [self.view addSubview:passwordLabel];    _passwordTextField = [[UITextFieldalloc]initWithFrame:CGRectMake(_userNameTextField.frame.origin.x, passwordLabel.frame.origin.y, _userNameTextField.frame.size.width, _userNameTextField.frame.size.height)];    _passwordTextField.placeholder =@"请输入密码";    _passwordTextField.borderStyle =3;    [self.view addSubview:_passwordTextField];    _loginButton = [UIButtonbuttonWithType:UIButtonTypeSystem];    _loginButton.frame =CGRectMake(170,300,50,50);    _loginButton.titleLabel.font = [UIFontsystemFontOfSize:25];    [_loginButton setTitle:@"登陆"forState:UIControlStateNormal];    [_loginButton addTarget:selfaction:@selector(didClickLoginButton) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:_loginButton];    _registerButton = [UIButtonbuttonWithType:UIButtonTypeSystem];    _registerButton.frame =CGRectMake(170,410,50,50);    _registerButton.titleLabel.font = [UIFontsystemFontOfSize:25];    [_registerButton setTitle:@"注册"forState:UIControlStateNormal];    [_registerButton addTarget:selfaction:@selector(jumpToRegister) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:_registerButton];}-(void)didClickLoginButton{    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:_userNameTextField.text password:_passwordTextField.text completion:^(NSDictionary*loginInfo, EMError *error) {if(!errorState of Qatar{//要是验证客户名和密码没不符合规律就跳转到亲密的朋友列表分界面[self.navigationController pushViewController:[[FriendListViewController alloc]init] animated:YES];        }else{// 彰显错误消息的告诫NSLog(@"%@",error卡塔尔;        }    } onQueue:dispatch_get_main_queue()];}-(void卡塔尔jumpToRegister{//跳转到注册分界面RegisterViewController *registerVC = [[RegisterViewController alloc]init];    [self.navigationController presentViewController:registerVC animated:YEScompletion:nil];}- (void)didReceiveMemoryWarning {    [superdidReceiveMemoryWarning];// Dispose of any resources that can be recreated.}@end

self.chatInputBottomConstant.constant= kbHeight;

// 点击空白处收键盘-fingerTapped:(UITapGestureRecognizer *)gestureRecognizer {

本条分界面很简短,大部分都是分界面搭建,当点击登入时会调用

//增多动漫

[self.view endEditing:YES];

[[EaseMob sharedInstance].chatManagerasyncLoginWithUsername:_userNameTextField.textpassword:_passwordTextField.textcompletion:^(NSDictionary *loginInfo, EMError *error)

[UIViewanimateWithDuration:0.25animations:^{

}

以此艺术有2个参数,叁个客商名,三个是密码,十分轻松猜到那正是印证你的客商名和密码是不是科学,借使没有错就跳转到好朋友列表界面,固然不对就可以在调节台打字与印刷相应的错误.

[self.viewlayoutIfNeeded];

  • textFieldShouldReturn:(UITextField *卡塔尔国textField {// 此处发送音讯// 3.创立EMChatText 对象EMChatText *chatText = [[EMChatText alloc] initWithText:textField.text];

    // 2.成立body 对象,发现需求chatTextEMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:chatText];

    // 1.成立消息,发掘body 对象EMMessage *emsg = [[EMMessage alloc] initWithReceiver:self.buddy.username bodies:@[body]];

    // 0.要发送音信,发现需求创设音信// 异步方法,发送一条音讯// 待发送的音信对象和发送后的信息对象是同一个对象,在出殡和下葬进程中指标属性可能会被退换[[EaseMob sharedInstance].chatManager asyncSendMessage:emsgprogress:nilprepare:^(EMMessage *message, EMError *error卡塔尔(قطر‎ {// 就要发送时间的回调}onQueue:nilcompletion:^(EMMessage *message, EMError *error卡塔尔(قطر‎ {// 发送停止时的回调if {NSLog;// 清空文本输入款textField.text = nil;// 发送成功之后将键盘退回去[textField resignFirstResponder];// 刷新分界面[self binge_reloadChatMsgs];}}onQueue:nil];

点击注册就跳转到注册界面.

}];

注册分界面

}

// 发送成功之后 刷新列表 return YES;

图片 4

#pragma mark键盘退出时会触发的章程

}

挂号分界面

-(void)kbWillHide:(NSNotification*)noti{

  • binge_reloadChatMsgs {// 首先刷新的时候要移除本来就有的对象[self.chatMsgs removeAllObjects];

    // 取得当前的对话对象 一个传username 另三个传谈心样式/*@brief 会话类型@constant eConversationTypeChat 单聊会话@constant eConversationTypeGroupChat 群聊会话@constant eConversationTypeChatRoom 闲谈室会话*/EMConversation *conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:self.buddy.username conversationType:eConversationTypeChat];// 获得会话中的谈天记录 (从数据库中加载新闻卡塔尔(قطر‎NSArray *msgs = [conversation loadAllMessages];// 放进可变数组中 改造多少[self.chatMsgs addObjectsFromArray:msgs];

    // 刷新表格[self.tableView reloadData];// 滚到最下边

是因为第一次登入风尚未账号,所以先得注册.先看看代码:

//inputToolbar恢复生机原来之处

}

#import"RegisterViewController.h"#import@interfaceRegisterViewController()@property(nonatomic,strong)UITextField*userNameTextField;//用户名@property(nonatomic,strong)UITextField*passwordTextField;//密码@property(nonatomic,strong)UIButton*registerButton;//注册按键@end@implementationRegisterViewController- (void卡塔尔viewDidLoad {    [superviewDidLoad];self.view.backgroundColor = [UIColorwhiteColor];self.navigationController.navigationBar.translucent =NO;self.title =@"登录界面";UILabel*usernameLabel = [[UILabelalloc]initWithFrame:CGRectMake(20,100,80,50)];    usernameLabel.text =@"用户名";    usernameLabel.font = [UIFontsystemFontOfSize:25];    [self.view addSubview:usernameLabel];    _userNameTextField = [[UITextFieldalloc]initWithFrame:CGRectMake(usernameLabel.frame.origin.x

self.chatInputBottomConstant.constant=0;

  • binge_observerKeyboardFrameChange {

    // 监听键盘 对相应的构造做改革[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillChangeFrameNotificationobject:nilqueue:[NSOperationQueue mainQueue]// 在哪些线程试行usingBlock:^(NSNotification * _Nonnull note) {NSLog(@"%s,line = %d,note = %@",FUNCTION,LINE,note);

     /* note.userInfo 布局参数 UIKeyboardAnimationCurveUserInfoKey = 7; UIKeyboardAnimationDurationUserInfoKey = "0.25"; UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {414, 271}}"; UIKeyboardCenterBeginUserInfoKey = "NSPoint: {207, 600.5}"; UIKeyboardCenterEndUserInfoKey = "NSPoint: {207, 871.5}"; UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 465}, {414, 271}}"; UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 736}, {414, 271}}"; UIKeyboardIsLocalUserInfoKey = 1; self.view 可以根据 end.oriY 来进行布局更改 */ // 初始高度 CGFloat endY = [note.userInfo [UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y; // 触发的键盘高度 CGFloat tempY = endY - self.view.bounds.size.height; self.view.frame = CGRectMake(0, tempY, self.view.bounds.size.width, self.view.bounds.size.height); // 添加动画 CGFloat duration = [note.userInfo [UIKeyboardAnimationDurationUserInfoKey] floatValue]; [UIView animateWithDuration:duration animations:^{ [self.view setNeedsLayout]; }]; }];
    
  • usernameLabel.frame.size.width 10, usernameLabel.frame.origin.y,250,50)];    _userNameTextField.borderStyle =3;    _userNameTextField.placeholder =@"请输入客户名";    [self.view addSubview:_userNameTextField];UILabel*passwordLabel = [[UILabelalloc]initWithFrame:CGRectMake(usernameLabel.frame.origin.x, usernameLabel.frame.origin.y usernameLabel.frame.size.height 10, usernameLabel.frame.size.width, usernameLabel.frame.size.height)];    passwordLabel.text =@"密码";    passwordLabel.font = [UIFontsystemFontOfSize:25];    [self.view addSubview:passwordLabel];    _passwordTextField = [[UITextFieldalloc]initWithFrame:CGRectMake(_userNameTextField.frame.origin.x, passwordLabel.frame.origin.y, _userNameTextField.frame.size.width, _userNameTextField.frame.size.height)];    _passwordTextField.placeholder =@"请输入密码";    _passwordTextField.borderStyle =3;    [self.view addSubview:_passwordTextField];    _registerButton = [UIButtonbuttonWithType:UIButtonTypeSystem];    _registerButton.frame =CGRectMake(170,330,50,50);    _registerButton.titleLabel.font = [UIFontsystemFontOfSize:25];    [_registerButton setTitle:@"注册"forState:UIControlStateNormal];    [_registerButton addTarget:selfaction:@selector(didClickedRegisterButton:) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:_registerButton];UIButton*backButton = [UIButtonbuttonWithType:UIButtonTypeSystem];    backButton.frame =CGRectMake(170,280,50,50);    backButton.titleLabel.font = [UIFontsystemFontOfSize:25];    [backButton setTitle:@"返回"forState:UIControlStateNormal];    [backButton addTarget:selfaction:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:backButton];}-(void)backAction{    [selfdismissViewControllerAnimated:YEScompletion:nil];}-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*卡塔尔event{//点击显示屏时让键盘回笼[_passwordTextField resignFirstResponder];    [_userNameTextField resignFirstResponder];}-(voidState of QatardidClickedRegisterButton:(id卡塔尔sender{//  登录和注册有3种形式: 1. 联机方法 2. 通过delegate回调的异步方法。3.block异步方法//个中官方推荐应用block异步方法,所以自个儿这里就用block异步方法//发轫注册[[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:_userNameTextField.text password:_passwordTextField.text withCompletion:^(NSString*username,NSString*password, EMError *error) {if(!error卡塔尔 {NSLog(@"注册成功"State of Qatar;            [selfdismissViewControllerAnimated:YEScompletion:nil];        }else{NSLog(@"%@",error);        }    } onQueue:dispatch_get_main_queue()];}- (void)didReceiveMemoryWarning {    [superdidReceiveMemoryWarning];// Dispose of any resources that can be recreated.}/*

}

}

#pragma mark - Navigation

//4.打消监听者

@end

// In a storyboard-based application, you will often want to do a little preparation before navigation

-(void)dealloc{

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

[[NSNotificationCenterdefaultCenter]removeObserver:self];

}

}

@end

15.闲谈分界面-接受方cell的制版

其一界面也专程轻便,除了分界面搭建,就只有那些情势:

经过深入分析,cell有三体系型:选用方cell、发送方cell、时间cell。

[[EaseMob sharedInstance].chatManagerasyncRegisterNewAccount:_userNameTextField.textpassword:_passwordTextField.textwithCompletion:^(NSString *username, NSString *password, EMError *error)

在刚刚拖入的tableview上拖二个cell重命名字为receivecell,再改cell中拖入控件并自行构造,给cell设置重用标志为receivecell

一共三个参数,正是客商名和密码,然后判别顾客名和密码是不是可用,如若可用就回到到登入分界面.

在乎:结构新闻框:思想:尾部为图片,下面为label,先构造label,然后构造imageview,让他与label大小同等,然后修改节制使iamgeview周边都比label相近大学一年级些。

亲密的朋友列表分界面

A.结构label:Label构造为离开顶上部分15,左边20。换行:点击label-lines = 0、(设置label最大幅面)点击尺子- preferred width = 242勾选,回车

图片 5

B.构造uiiamgeview:cell中拖三个UIimageview,从左边的列表中找到该imageview,拖到label的背后,同期选中label、iamgeview、设置四边距都对齐节制,然后update,给iamgeview增添背景图片,图片拉伸:点击imageview-streching-x:0.5/y:0.7,别的都为0。找到iamgeview的具备约束,给相近约束分别调十一个区间大小。

知音列表分界面

自定义cell,view-ChatCell,将刚才storyboard中的cell的class改为此类。将地点十三分label拖线到.h文件(必得)为属性

那边自个儿只加了叁个基友叫xiaomei.

调节器中数据源和代理的章程落成如下(测量试验而已卡塔尔:

好友分界面是何等的呢,大家先看看代码:

-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{

#import"FriendListViewController.h"#import"AddFriendViewController.h"#import"ChatViewController.h"#import@interfaceFriendListViewController()@property(nonatomic,strong)NSMutableArray*listArray;@property(nonatomic,strong)UITableView*tableView;@end@implementationFriendListViewController-(void)viewWillAppear:(BOOL)animated{    [superviewWillAppear:animated];    }-(void)loadView{    [superloadView];self.view.backgroundColor =

return20;

[UIColorwhiteColor];//左边注销按键self.navigationItem.leftBarButtonItem

[[UIBarButtonItemalloc]initWithTitle:@"注销"style:UIBarButtonItemStylePlaintarget:selfaction:@selector(didClickedCancelButton)];self.title =@"好友";    [[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray*buddyList, EMError *error) {if(!error卡塔尔 {NSLog(@"获取成功 -- %@", buddyList卡塔尔国;            [_listArray removeAllObjects];            [_listArray addObjectsFromArray:buddyList];            [_tableView reloadData];        }    } onQueue:dispatch_get_main_queue()];}- (void)viewDidLoad {    [superviewDidLoad];    _listArray = [NSMutableArraynew];self.navigationItem.rightBarButtonItem = [[UIBarButtonItemalloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAddtarget:selfaction:@selector(addbuttonAction)];    _tableView = [[UITableViewalloc]initWithFrame:self.view.frame];    _tableView.delegate =self;    _tableView.dataSource =self;    _tableView.tableFooterView = [[UIViewalloc]init];    [self.view addSubview:_tableView];//签协议[ [EaseMob sharedInstance].chatManager addDelegate:selfdelegateQueue:dispatch_get_main_queue()];}-(void卡塔尔didClickedCancelButton{//注销客户[[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:YES];    [self.navigationController popViewControllerAnimated:YES];}-(void)addbuttonAction{    [self.navigationController pushViewController:[[AddFriendViewController alloc]init] animated:YES];}# pragma mark - Table View Data Source- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {return_listArray.count;}-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath{return50;}- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {staticNSString*identifier =@"cell";UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:identifier];if(!cell) {        cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleValue1reuseIdentifier:identifier];    }    EMBuddy * buddy = _listArray[indexPath.row];    cell.textLabel.text = buddy.username;returncell;}- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {    ChatViewController * chatVC = [[ChatViewController alloc]init];    EMBuddy * buddy = _listArray[indexPath.row];    chatVC.name = buddy.username;    [self.navigationController pushViewController:chatVC animated:YES];}-(void)didReceiveBuddyRequest:(NSString*)username message:(NSString*)message{UIAlertController* alertController = [UIAlertControlleralertControllerWithTitle:[NSStringstringWithFormat:@"收到来自%@的诉求", username] message:message preferredStyle:(UIAlertControllerStyleAlert)];UIAlertAction* acceptAction = [UIAlertActionactionWithTitle:@"好"style:(UIAlertActionStyleDefault) handler:^(UIAlertAction*  action) {        EMError * error;// 同意基友诉求的点子if([[EaseMob sharedInstance].chatManager acceptBuddyRequest:username error:&error] && !errorState of Qatar{NSLog(@"发送同意成功"State of Qatar;            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{                [[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray*buddyList, EMError *error) {if(!errorState of Qatar {NSLog(@"获取成功 -- %@", buddyListState of Qatar;                        [_listArray removeAllObjects];                        [_listArray addObjectsFromArray:buddyList];                        [_tableView reloadData];                    }                } onQueue:dispatch_get_main_queue()];            });        }    }];UIAlertAction* rejectAction = [UIAlertActionactionWithTitle:@"滚"style:(UIAlertActionStyleCancel) handler:^(UIAlertAction* _Nonnull action) {        EMError * error;// 拒却老铁需要的点子if([[EaseMob sharedInstance].chatManager rejectBuddyRequest:username reason:@"滚, 快滚!"error:&error] && !error卡塔尔(قطر‎{NSLog(@"发送谢绝成功"卡塔尔;        }    }];    [alertController addAction:acceptAction];    [alertController addAction:rejectAction];    [selfshowDetailViewController:alertController sender:nil];}- (void)didReceiveMemoryWarning {    [superdidReceiveMemoryWarning];// Dispose of any resources that can be recreated.}

第一,使用上边那些点子赢获得全部的知音,然后将好朋友归入你的数组,那样好友的音讯都在数组里了

[[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray*buddyList, EMError *error) {        if (!error卡塔尔(قطر‎ {            NSLog(@"获取成功 -- %@", buddyListState of Qatar;[_listArray removeAllObjects];[_listArray addObjectsFromArray:buddyList];[_tableView reloadData];}    } onQueue:dispatch_get_main_queue()];

tableView没行的新闻经过上边那么些措施,刚才已经把拥有老铁的音讯方法数组里了,那么就能够因而EMBuddy * buddy =

_listArray[indexPath.row]其一法子得到单个好朋友消息,用  cell.textLabel.text =

buddy.username给每个cell的text赋值.

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {staticNSString*identifier =@"cell";UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:identifier];if(!cell) {        cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleValue1reuseIdentifier:identifier];    }    EMBuddy * buddy = _listArray[indexPath.row];    cell.textLabel.text = buddy.username;returncell;}

当别人想加你为亲密的朋友时,会调用这一个方法.先弹出二个提醒框,然后依照你的选择而去领受恐怕回绝.假设选择,就再一次导入三次数据,然后刷新tableView.假若谢绝就调用拒却的方法.那并简单驾驭吧.

-(void)didReceiveBuddyRequest:(NSString *)usernamemessage:(NSString *)message{ UIAlertController * alertController = [UIAlertControlleralertControllerWithTitle:[NSStringstringWithFormat:@"收到来自%@的央浼", username]message:messagepreferredStyle:(UIAlertControllerStyleAlert)];    UIAlertAction * acceptAction = [UIAlertActionactionWithTitle:@"好"style:(UIAlertActionStyleDefault)handler:^(UIAlertAction *  action) {        EMError * error;// 同意老铁央浼的不二诀窍if([[EaseMob sharedInstance].chatManageracceptBuddyRequest:usernameerror:&error] && !error卡塔尔 {            NSLog(@"发送同意成功"卡塔尔;                [[EaseMob sharedInstance].chatManagerasyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {if(!error卡塔尔国 {                        NSLog(@"获取成功 -- %@", buddyList卡塔尔国;                        [_listArray removeAllObjects];                        [_listArrayaddObjectsFromArray:buddyList];                        [_tableView reloadData];                    }                }onQueue:dispatch_get_main_queue()];        }    }];    UIAlertAction * rejectAction = [UIAlertActionactionWithTitle:@"滚"style:(UIAlertActionStyleCancel)handler:^(UIAlertAction * _Nonnull action) {        EMError * error;// 拒绝好朋友央求的格局if([[EaseMob sharedInstance].chatManagerrejectBuddyRequest:usernamereason:@"滚, 快滚!"error:&error] && !error卡塔尔国 {            NSLog(@"发送谢绝成功"卡塔尔(قطر‎;        }    }];    [alertControlleraddAction:acceptAction];    [alertControlleraddAction:rejectAction];    [selfshowDetailViewController:alertControllersender:nil];

闲谈分界面

图片 6

聊天分界面

在看谈心分界面以前先需求自定义叁个闲聊输入框,正是下面这些带三个text田野同志和button的.

DialogBoxView.m

#import"DialogBoxView.h"@interfaceDialogBoxView()@property(nonatomic,strong)UITextField* draftTextField;@property(nonatomic,strong)UIButton* sendButton;@end@implementationDialogBoxView- (instancetype)initWithFrame:(CGRect)frame{self= [superinitWithFrame:frame];if(self) {        [selfinitView];    }returnself;}- (void)initView{    [selfsetBackgroundColor:[UIColorcolorWithWhite:0.9alpha:1]];    _draftTextField = [[UITextFieldalloc] initWithFrame:CGRectMake(5,5,self.frame.size.width -100,self.frame.size.height -10)];    [_draftTextField setBorderStyle:(UITextBorderStyleRoundedRect)];    [_draftTextFieldsetPlaceholder:@"说点什么呢"];    [_draftTextField setFont:[UIFontsystemFontOfSize:13]];    [selfaddSubview:_draftTextField];    _sendButton = [UIButtonbuttonWithType:(UIButtonTypeCustom)];    [_sendButton setFrame:CGRectMake(self.frame.size.width -90,5,85,self.frame.size.height -10)];    [_sendButton setBackgroundColor:[UIColorcolorWithRed:1green:0blue:128/255.0alpha:1]];    [_sendButton setTitle:@"发送"forState:(UIControlStateNormal)];    [_sendButton setTitleColor:[UIColorwhiteColor] forState:UIControlStateNormal];    [_sendButton.titleLabel setFont:[UIFontboldSystemFontOfSize:15]];    [_sendButton.layer setMasksToBounds:YES];    [_sendButton.layer setCornerRadius:4];    [_sendButton addTarget:selfaction:@selector(didSendButtonClicked:) forControlEvents:(UIControlEventTouchUpInside)];    [selfaddSubview:_sendButton];}- (void)didSendButtonClicked:(UIButton*)sender {if(self.buttonClicked) {self.buttonClicked(_draftTextField.text);    }    _draftTextField.text =@"";}- (NSString*)draftText {return_draftTextField.text;}/*

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect {

// Drawing code

}

*/@end

本条大约的自定义view没什么好说的,关键是她的.h文件

DialogBoxView.h

#importtypedefvoid(^ButtonClicked)(NSString* draftText);@interfaceDialogBoxView:UIView@property(nonatomic,copy) ButtonClicked buttonClicked;@end

这里用到二个block,当点击按键时会调用那些block.

接过看看闲聊分界面包车型客车代码吧.

#import"ChatViewController.h"#import"DialogBoxView.h"#import@interfaceChatViewController()@property(nonatomic,strong)UITableView*tableView;@property(nonatomic,strong)EMConversation *conversation;@property(nonatomic,strong)DialogBoxView *dialogBoxView;@end@implementationChatViewController-(void)loadView{    [superloadView];self.title = _name;self.navigationController.navigationBar.translucent =NO;    _tableView = [[UITableViewalloc]initWithFrame:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height -50)];    _tableView.delegate =self;    _tableView.dataSource =self;    _tableView.tableFooterView = [[UIViewalloc]init];    [self.view addSubview:_tableView];}- (void)viewDidLoad {    [superviewDidLoad];    [_tableView setAllowsSelection:NO];    [selfregisterForKeyboardNotifications];    _dialogBoxView = [[DialogBoxView alloc]initWithFrame:CGRectMake(0,self.view.frame.size.height -114,self.view.frame.size.width,50)];    __weaktypeof(self) weakSelf =self;    _dialogBoxView.buttonClicked = ^(NSString* draftText){        [weakSelf sendMessageWithDraftText:draftText];    };    [self.view addSubview:_dialogBoxView];    [[EaseMob sharedInstance].chatManager addDelegate:selfdelegateQueue:dispatch_get_main_queue()];    [selfreloadChatRecords];}- (void)viewWillDisappear:(BOOL)animated {    [superviewWillDisappear:animated];// 移除布告中央[selfremoveForKeyboardNotifications];// 移除代理[[EaseMob sharedInstance].chatManager removeDelegate:self];}# pragma mark - Send Message/**

*  使用草稿发送一条音信

*

*  @param draftText 草稿

*/- (void)sendMessageWithDraftText:(NSString*)draftText {    EMChatText * chatText = [[EMChatText alloc] initWithText:draftText];    EMTextMessageBody * body = [[EMTextMessageBody alloc] initWithChatObject:chatText];// 生成messageEMMessage * message = [[EMMessage alloc] initWithReceiver:self.name bodies:@[body]];    message.messageType = eMessageTypeChat;// 设置为单聊新闻[[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nilprepare:^(EMMessage *message, EMError *error卡塔尔(قطر‎ {// 策动发送} onQueue:dispatch_get_main_queue() completion:^(EMMessage *message, EMError *error) {        [selfreloadChatRecords];// 发送实现} onQueue:dispatch_get_main_queue()];}# pragma mark - Receive Message/**

*  当收到了一条消息时

*

*  @param message 消息布局体

*/- (void)didReceiveMessage:(EMMessage *)message {    [selfreloadChatRecords];}# pragma mark - Reload Chat Records/**

*  重新加载TableView上边展现的闲聊音讯, 并移动到终极一行

*/- (void)reloadChatRecords {    _conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:self.name conversationType:eConversationTypeChat];    [_tableView reloadData];if([_conversation loadAllMessages].count >0) {        [_tableView scrollToRowAtIndexPath:[NSIndexPathindexPathForRow:[_conversation loadAllMessages].count -1inSection:0] atScrollPosition:(UITableViewScrollPositionBottom) animated:YES];    }}# pragma mark - Keyboard Method/**

*  注册通告宗旨

*/- (void卡塔尔(قطر‎registerForKeyboardNotifications{// 使用NSNotificationCenter 注册观望当键盘要出新时[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(didKeyboardWillShow:) name:UIKeyboardWillShowNotificationobject:nil];// 使用NSNotificationCenter 注册观看当键盘要藏匿时[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(didKeyboardWillHide:) name:UIKeyboardWillHideNotificationobject:nil];}/**

*  移除公告大旨

*/- (void)removeForKeyboardNotifications {    [[NSNotificationCenterdefaultCenter] removeObserver:self];}/**

*  键盘将在弹出

*

*  @param notification 通知

*/- (void)didKeyboardWillShow:(NSNotification*)notification {NSDictionary* info = [notification userInfo];CGSizekeyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;NSLog(@"%f", keyboardSize.height卡塔尔国;//输入框地点动漫加载[selfbegainMoveUpAnimation:keyboardSize.height];}/**

*  键盘就要掩没

*

*  @param notification 通知

*/- (void)didKeyboardWillHide:(NSNotification*)notification {    [selfbegainMoveUpAnimation:0];}/**

*  初叶实践键盘改换后对应视图的变动

*

*  @param height 键盘的冲天

*/- (void)begainMoveUpAnimation:(CGFloat)height {    [UIViewanimateWithDuration:0.3animations:^{        [_dialogBoxView setFrame:CGRectMake(0,self.view.frame.size.height - (height 40), _dialogBoxView.frame.size.width, _dialogBoxView.frame.size.height)];    }];    [_tableView layoutIfNeeded];if([_conversation loadAllMessages].count >1) {        [_tableView scrollToRowAtIndexPath:[NSIndexPathindexPathForRow:_conversation.loadAllMessages.count -1inSection:0] atScrollPosition:(UITableViewScrollPositionMiddle) animated:YES];    }}# pragma mark - Table View Data Source- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {return_conversation.loadAllMessages.count;}- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {staticNSString*identifier =@"cell";UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:identifier];if(!cell) {        cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleValue1reuseIdentifier:identifier];    }    EMMessage * message = _conversation.loadAllMessages[indexPath.row];    EMTextMessageBody * body = [message.messageBodies lastObject];//决断发送的人是不是是当前闲谈的人,左边是对面发过来的,左边是仁慈发过去的if([message.to isEqualToString:self.name]) {        cell.detailTextLabel.text = body.text;        cell.detailTextLabel.textColor = [UIColorredColor];        cell.textLabel.text =@"";        cell.textLabel.textColor = [UIColorblueColor];    }else{        cell.detailTextLabel.text =@"";        cell.textLabel.text = body.text;        cell.detailTextLabel.textColor = [UIColorredColor];        cell.textLabel.textColor = [UIColorblueColor];    }returncell;}- (void)didReceiveMemoryWarning {    [superdidReceiveMemoryWarning];// Dispose of any resources that can be recreated.}@end

那之中也没怎么困难,也可能有注释,相信大家能懂.

最后看看最终的成果图吧.

图片 7

成品图

好了,前几日就到此处,祝我们每天欢畅

举例认为小编的文章对您有用,请随便表扬。您的协理将慰勉笔者一而再一而再再而三创作!

}

-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath{

return200;

}

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{

staticNSString*ID =@"ReceiverCell";

ChatCell*cell = [tableViewdequeueReusableCellWithIdentifier:ID];

//展现内容

cell.chatLabel.text=@"asrqwerqwerqwerqwerqwfaskdjlfalsk;dfjalksjdflaksjdfa;sjdfklajsdkfljasfkal;sdkfjalksjdfa;jsdflkajsdf;lajskdf;las";

returncell;

}

16.谈心分界面-发送方cell的制版

1卡塔尔.tableview中再拖三个cell,同理搭建sendcell(注意:将label脱线到cell中的同三个属性中卡塔尔国

2State of Qatar.设置cell的万丈:在自定义cell中贯彻总括cell的中度)

//特地用来总计中度的贰个cell(注意精晓)

#import

staticNSString*ReceiverCell =@"ReceiverCell";

staticNSString*SenderCell =@"SenderCell";

@interfaceChatCell :UITableViewCell

@property(weak,nonatomic)IBOutletUILabel*chatLabel;

-(CGFloat)cellHeghit;

@end

#import"ChatCell.h"

@implementationChatCell

/**返回cell的高度*/

-(CGFloat)cellHeghit{

//1.再度构造子控件

[selflayoutIfNeeded];

return5 10 self.chatLabel.bounds.size.height 10 5;

}

@end

3State of Qatar.调节器中贯彻的艺术

a.添加属性

@property(weak,nonatomic)IBOutletUITableView*tableView;

/**数据源*/

@property(nonatomic,strong)NSMutableArray*dataSources;

/**估测计算中度的cell工具对象(正是二个工具,给自己文字长度笔者就会计算中度卡塔尔国*/

@property(nonatomic,strong)ChatCell*chatCellTool;

b.viewdidload开端化数据源

-(NSMutableArray*)dataSources{

if(!_dataSources) {

_dataSources= [NSMutableArrayarray];

}

return_dataSources;

}

//伊始化数(大多少个长的State of Qatar据

[self.dataSourcesaddObject:@"xcsafasdffsadfa"];

[self.dataSourcesaddObject:@"xcsafasdfsadxcssafasdfsadfafa"];

[self.dataSourcesaddObject:@"xcsafasdfxcsaadfasadfa"];

//给总计中度的cell工具对象赋值(正是初叶化工具对象,也得以为sendcell卡塔尔

self.chatCellTool= [self.tableViewdequeueReusableCellWithIdentifier:ReceiverCell];

c.重新完结数据源方法

-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{

returnself.dataSources.count;

}

-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath{

//设置label的数据

#warning总计中度与前,必定要给chatLabel.text赋值

self.chatCellTool.chatLabel.text=self.dataSources[indexPath.row];

return[self.chatCellToolcellHeghit];

}

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{

ChatCell*cell =nil;

if(indexPath.row%2==0卡塔尔 {//发送方的cell

cell = [tableViewdequeueReusableCellWithIdentifier:SenderCell];

}else{//选取发方的cell

cell = [tableViewdequeueReusableCellWithIdentifier:ReceiverCell];

}

//展现内容

cell.chatLabel.text=self.dataSources[indexPath.row];

returncell;

}

音信管理

消息:IM人机联作实体,在SDK中对应的品类是EMMessage。EMMessage由EMMessageBody组成.

小结:与消息相关的网络必要都用到[[EMClientsharedClient].chatManager谈天管理者

赢得壹个人的对话列表用EMConversation类

17.闲聊分界面-发送闲聊音信

步骤:

在mainstoryboard中找到聊天分界面包车型大巴输入框textView,点击-return-send

监听该send事件:拖线该text田野先生的代办到闲聊调节器(ChatViewController)。调控器遵守代理(UITextViewDelegate),并落实代理方法

导入头文件:#import "EMSDK.h"(用多了足以加上到pch文件中)

1State of Qatar.给该调节器增多三个外表属性

//要发赠送外人的名字

@property(nonatomic,copy)NSString*buddy;

2卡塔尔.在电视发表录调整器(AddressBookViewController)中传值,代码如下:

-(void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender{

//往谈心调控器传递叁个buddy的值

iddestVC = segue.destinationViewController;

if([destVCisKindOfClass:[ChatViewControllerclass]]) {

//获取点击的行

NSIntegerselectedRow = [self.tableViewindexPathForSelectedRow].row;

ChatViewController*chatVc = destVC;

chatVc.buddy=self.boddyList[selectedRow];

}

}

3卡塔尔国.闲聊调整器(ChatViewController)中发送消息代码如下

#pragma mark -UITextViewDelegate

-(void)textViewDidChange:(UITextView*)textView{

//监听Send事件--剖断最后的二个字符是否换行字符(因为点击send时,text田野会换行)

if([textView.texthasSuffix:@"n"]) {

NSLog(@"发送操作"State of Qatar;

[selfsendMessage:textView.text];

//清空textView的文字

textView.text=nil;

}

}

//发送音信

-(void)sendMessage:(NSString*)text{

//把最终二个换行字符去除

#warning换行字符只占用三个尺寸

text = [textsubstringToIndex:text.length-1];

//消息=消息头 消息体

#warning各样消息类型对象分裂的音信体

//EMTextMessageBody:文字

//EMImageMessageBody:图片

//EMLocationMessageBody:位置

//EMVoiceMessageBody:语音

//EMVideoMessageBody:视频

//EMFileMessageBody:文件

//EMCmdMessageBody:透传

//1.创办理文件字新闻体

EMTextMessageBody*body = [[EMTextMessageBodyalloc]initWithText:text];

NSString*from = [[EMClientsharedClient]currentUsername];

//2.生成Message音信指标

EMMessage*message = [[EMMessagealloc]initWithConversationID:self.buddyfrom:fromto:self.buddybody:bodyext:nil];

message.chatType=EMChatTypeChat;//设置为单聊讯息

//音信类型为:

//EMChatTypeChat:设置为单聊音讯

// EMChatTypeGroupChat:设置为群聊音讯

//EMChatTypeChatRoom:设置为闲聊室新闻

//3.出殡和下葬消息

//发送全部类别的音信都用那几个接口,只是新闻类型区别

[[EMClientsharedClient].chatManagersendMessage:messageprogress:^(intprogress) {

}completion:^(EMMessage*message,EMError*error) {

NSLog(@"完结新闻发送%@",errorState of Qatar;

}];

// 4.把新闻加多到数据源,然后再刷新表格(发送完消息立即呈现)

[self.dataSourcesaddObject:message];

[self.tableViewreloadData];

// 5.把消息呈现在最上端(发送完音讯自动滚动到键盘最上部)

[selfscrollToBottom];

}

-(void)scrollToBottom{

//1.赢得最后一行

if(self.dataSources.count==0) {

return;

}

NSIndexPath*lastIndex = [NSIndexPathindexPathForRow:self.dataSources.count-1inSection:0];

[self.tableViewscrollToRowAtIndexPath:lastIndexatScrollPosition:UITableViewScrollPositionBottomanimated:YES];

}

18.聊天分界面-增多本地闲聊记录

1State of Qatar.在拉拉扯扯调控器中的viewdidload方法中丰硕当前navigation的title为很好的朋友的名字,加载本地闲谈记录

//彰显好朋友的名字

self.title=self.buddy;

//加载本地数据库闲谈记录(MessageV1)

[selfloadLocalChatRecords];

-(void)loadLocalChatRecords{

//要拿走本地闲扯记录使用会话对象

//获取一个会话

//EMConversationTypeChat单聊会话

//EMConversationTypeGroupChat群聊会话

//EMConversationTypeChatRoom谈心室会话

EMConversation*conversation = [[EMClientsharedClient].chatManagergetConversation:self.buddytype:EMConversationTypeChatcreateIfNotExist:YES];

//加载与当下闲谈客商全数闲话记录

// fromUser:若传老铁名字,则只会加载基友发的闲谈记录,若为nil加载双方的

longlongtimestamp = [[NSDatedate]timeIntervalSince1970] *1000 1;

[conversationloadMessagesWithType:EMMessageBodyTypeTexttimestamp:timestampcount:100fromUser:nilsearchDirection:EMMessageSearchDirectionUpcompletion:^(NSArray*aMessages,EMError*aError) {

//aMessages内部为EMMessage对象

//增添到数据源

[self.dataSourcesaddObjectsFromArray:aMessages];

[self.tableViewreloadData];

}];

}

2卡塔尔.在自定义cellChatCell中增加外界模型属性,并达成set方法,封装

/**新闻模型,内部set方法呈现文字*/

@property(nonatomic,strong)EMMessage*message;

-(void)setMessage:(EMMessage*)message{

_message= message;

// 1.获取新闻体

idbody = message.body;

if([bodyisKindOfClass:[EMTextMessageBodyclass]]卡塔尔国 {//文本消息

EMTextMessageBody*textBody = body;

self.chatLabel.text= textBody.text;

}elseif([bodyisKindOfClass:[EMVoiceMessageBodyclass]]卡塔尔(قطر‎{//语音新闻

self.chatLabel.text=@"【语音】";

}

else{

self.chatLabel.text=@"未知类型";

}

}

3State of Qatar.在闲聊调节器中期维更改tableview的数据源方法

-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{

returnself.dataSources.count;

}

-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath{

//设置label的数据

NSLog(@"%@",self.dataSources[indexPath.row]);

// 1.获取音讯模型

EMMessage*msg =self.dataSources[indexPath.row];

self.chatCellTool.message= msg;

return[self.chatCellToolcellHeghit];

}

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{

//1.先获取新闻模型

EMMessage*message =self.dataSources[indexPath.row];

ChatCell*cell =nil;

if([message.fromisEqualToString:self.buddy]) {//接收方

cell = [tableViewdequeueReusableCellWithIdentifier:ReceiverCell];

}else{//发送方

cell = [tableViewdequeueReusableCellWithIdentifier:SenderCell];

}

//展现内容

cell.message= message;

returncell;

}

29.谈天分界面-监听新闻回复(将对方发的音讯随时呈现在当下闲谈分界面)

闲谈调控器中的viewdidload中设置闲话微处理器代理并遵循合同EMChatManagerDelegate

[[EMClientsharedClient].chatManageraddDelegate:selfdelegateQueue:nil];

//实今世理方法

#pragma mark -EMChatManagerDelegate

//收到一条以上新闻

- (void)messagesDidReceive:(NSArray*)aMessages{

for(EMMessage*messageinaMessages) {

#warning from一定等于当前闲谈客商才方可刷新数据(当test1 - test7两个闲谈时,test8发过来的消息无法显得在该聊天记录分界面)

if([message.fromisEqualToString:self.buddy]) {

//1.把接受的新闻增多到数据源

[self.dataSourcesaddObject:message];

//2.刷新表格

[self.tableViewreloadData];

//3.显得数据到底层

[selfscrollToBottom];

}

}

}

20.周密闲聊输入框

达成输入框自动更改高度:

1卡塔尔.找到mainstoryboard中的谈天调控器分界面包车型客车ChatInputToolBar找到她的万丈属性,并拖线到闲谈调整器成为其个性

@property(weak,nonatomic)IBOutletNSLayoutConstraint*inputbarHeightConstant;

2卡塔尔国.在闲聊调整器ChatViewController中的监听文字退换的方式中丰硕:

#pragma mark -UITextViewDelegate

-(void)textViewDidChange:(UITextView*)textView{

//监视textView.contentOffset的变化

NSLog(@"contentOffset %@",NSStringFromCGPoint(textView.contentOffset));

// 1.计算TextView的中度,调度总体intputbar的莫斯中国科学技术大学学

CGFloattextViewH =0;

CGFloatminHeight =33;//textView最小的冲天

CGFloatmaxHeight =68;//textView最大的中度

//获取contentSize的高度(因为textView继承自scrollview)

CGFloatcontentHeight = textView.contentSize.height;

if(contentHeight < minHeight) {

textViewH = minHeight;

}elseif(contentHeight > maxHeight){

textViewH = maxHeight;

}else{

textViewH = contentHeight;

本文由澳门威利斯人发布于办公软件,转载请注明出处:集成环信的即时通讯,发送文本消息

关键词: 澳门威利斯人 日记本 消息 即时通讯 文本