环信

-------------------AppDelegate.m-------------------

#import "AppDelegate.h"

// 环信的头文件
#import <EaseMob.h>

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 注册环信SDK
    // 第一个参数 :APPkey 由应用名字#公司的ID构成
    // 第二个参数 :如果使用推送功能 则需要填推送证书的名字
    [[EaseMob sharedInstance] registerSDKWithAppKey:@"lutianyi#easemobsample" apnsCertName:@""];
    
    return YES;
}

- (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.
}
// App进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
}
// App将要从后台返回
- (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];
    [self saveContext];
}

----------------LoginViewController.m----------------

#import "LoginViewController.h"

#import "RegisterViewController.h"
#import "MessageViewController.h"
#import "RosterViewController.h"
#import "AppDelegate.h"
#import <EaseMob.h>

@interface LoginViewController ()

@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passWordTextField;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.userNameTextField.layer.borderWidth = 1;
    self.passWordTextField.layer.borderWidth = 1;
    
}

- (IBAction)loginButtonClicked:(id)sender
{
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:self.userNameTextField.text password:self.passWordTextField.text completion:^(NSDictionary *loginInfo, EMError *error)
    {
        if (!error)
        {
            NSLog(@"登录成功");
            MessageViewController *messageVC = [MessageViewController new];
            UINavigationController *messageNC = [[UINavigationController alloc] initWithRootViewController:messageVC];
            messageNC.title = @"消息";
            
            RosterViewController *rosterVC = [RosterViewController new];
            UINavigationController *rosterNC = [[UINavigationController alloc] initWithRootViewController:rosterVC];
            rosterNC.title = @"好友";
            
            UITabBarController *tabBar = [UITabBarController new];
            tabBar.viewControllers = @[messageNC, rosterNC];
            
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            app.window.rootViewController = tabBar;
        }
        else
        {
            NSLog(@"登录失败  error ==== %@", error);
        }
    } onQueue:dispatch_get_main_queue()];
}
- (IBAction)registerButtonClicked:(id)sender
{
    RegisterViewController *registerVC = [RegisterViewController new];
    registerVC = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"registerVC"];
    [self showViewController:registerVC sender:nil];
    
    __weak typeof(self) pSelf = self;
    registerVC.passValue = ^(NSString *userName, NSString *passWord)
    {
        pSelf.userNameTextField.text = userName;
        pSelf.passWordTextField.text = passWord;
    };
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

----------------RegisterViewController.h--------------

#import <UIKit/UIKit.h>

typedef void(^myBlock)(NSString *, NSString *);

@interface RegisterViewController : UIViewController

@property (nonatomic, copy)myBlock passValue;

@end

---------------RegisterViewController.m--------------

#import "RegisterViewController.h"

#import <EaseMob.h>

@interface RegisterViewController ()

@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passWordTextField;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.userNameTextField.layer.borderWidth = 1;
    self.passWordTextField.layer.borderWidth = 1;
    
}

- (IBAction)registerButtonClicked:(id)sender
{
    [[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:self.userNameTextField.text password:self.passWordTextField.text withCompletion:^(NSString *username, NSString *password, EMError *error)
    {
        if (!error)
        {
            NSLog(@"注册成功");
            self.passValue(self.userNameTextField.text, self.passWordTextField.text);
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        else
        {
            NSLog(@"注册失败 error === %@", error);
        }
    } onQueue:dispatch_get_main_queue()];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

---------------MessageViewController.m--------------

#import "MessageViewController.h"

#import "ChatViewController.h"
#import <EaseMob.h>

@interface MessageViewController ()<UITableViewDataSource, UITableViewDelegate, EMChatManagerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"最新消息";
    
    self.dataArray = [NSMutableArray array];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self reloadConversation];
}
// 收到一条消息
- (void)didReceiveMessage:(EMMessage *)message
{
    [self reloadConversation];
}

// 获取数据 获取当前用户的会话列表
- (void)reloadConversation
{
    [self.dataArray removeAllObjects];
    [self.dataArray addObjectsFromArray:[[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES]];
    [self.tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:@"CELL"];
    }
    
    // 聊天会话对象
    EMConversation *conversation = self.dataArray[indexPath.row];
    // chatter 会话对象中的名字
    cell.textLabel.text = conversation.chatter;
    
    // message 聊天消息对象 conversation.latestMessage 最后一条消息
    EMMessage *message = conversation.latestMessage;
    // EMTextMessageBody 消息体对象,message.messageBodies 聊天消息中保存的消息体对象
    // 获取到最后一次发送的消息
    EMTextMessageBody *body = message.messageBodies.lastObject;
    cell.detailTextLabel.text = body.text;
    return cell;
}

- (void)didReceiveBuddyRequest:(NSString *)username message:(NSString *)message
{
    NSString *title = [NSString stringWithFormat:@"请求添加您为好友"];
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
    {
        // 环信的错误类 相当于NSError
        EMError *error = nil;
        BOOL succeed = [[EaseMob sharedInstance].chatManager acceptBuddyRequest:username error:&error];
        if (succeed && !error)
        {
            NSLog(@"接受成功");
        }
        else
        {
            NSLog(@"接收好友请求失败,error ==== %@", error);
        }
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"残忍拒绝" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
    {
        // 环信的错误类 相当于NSError
        EMError *error = nil;
        BOOL succeed = [[EaseMob sharedInstance].chatManager rejectBuddyRequest:username reason:@"我拒绝" error:&error];
        if (succeed && !error)
        {
            NSLog(@"拒绝成功");
        }
        else
        {
            NSLog(@"拒绝好友请求失败,error ==== %@", error);
        }
    }];
    [controller addAction:action];
    [controller addAction:action1];
    [self presentViewController:controller animated:YES completion:nil];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChatViewController *chatVC = [ChatViewController new];
    
    EMConversation *conversation = self.dataArray[indexPath.row];
    // chatter 会话对象的用户名
    chatVC.chatter = conversation.chatter;
    
    [self showViewController:chatVC sender:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

---------------RosterViewController.m----------------

#import "RosterViewController.h"

#import "AddFriendsViewController.h"
#import "ChatViewController.h"
#import <EaseMob.h>

@interface RosterViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation RosterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"好友列表";
    
    self.dataArray = [NSMutableArray array];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CELL"];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addButtonClicked)];
}
- (void)addButtonClicked
{
    AddFriendsViewController *addFriendsVC = [AddFriendsViewController new];
    addFriendsVC = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"addFriendsVC"];
    [self presentViewController:addFriendsVC animated:YES completion:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self reloadRoster];
}
- (void)reloadRoster
{
    [self.dataArray removeAllObjects];
    [[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
        [self.dataArray removeAllObjects];
        [self.dataArray addObjectsFromArray:buddyList];
        [self.tableView reloadData];
    } onQueue:dispatch_get_main_queue()];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
    // EMBuddy 好友的信息描述类
    EMBuddy *buddy = self.dataArray[indexPath.row];
    // username 好友名字
    cell.textLabel.text = buddy.username;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChatViewController *chatVC = [[ChatViewController alloc] init];
    EMBuddy *buddy = self.dataArray[indexPath.row];
    chatVC.chatter = buddy.username;
    [self showViewController:chatVC sender:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

----------------ChatViewController.h----------------

#import <UIKit/UIKit.h>

@interface ChatViewController : UIViewController

@property (nonatomic, copy) NSString *chatter;

@end

----------------ChatViewController.m----------------

#import "ChatViewController.h"

#import <EaseMob.h>

@interface ChatViewController ()<UITableViewDataSource, UITableViewDelegate, EMChatManagerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) EMConversation *conversation;

@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(sendMessage)];
    
    [self reloadMessage];
}

-(void)reloadMessage
{
    self.conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:self.chatter conversationType:eConversationTypeChat];
    [self.tableView reloadData];
}

- (void)sendMessage
{
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"发送消息" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
    {
        
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"发送" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
    {
        // 聊天的文本对象
        EMChatText *text = [[EMChatText alloc] initWithText:controller.textFields.firstObject.text];
        // 聊天的文本消息体对象
        EMTextMessageBody *textMessageBody = [[EMTextMessageBody alloc] initWithChatObject:text];
        // 聊天消息类
        EMMessage *message = [[EMMessage alloc] initWithReceiver:self.chatter bodies:@[textMessageBody]];
        // 发送这条消息
        [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil prepare:^(EMMessage *message, EMError *error)
        {
            // 准备发送
        } onQueue:dispatch_get_main_queue() completion:^(EMMessage *message, EMError *error)
        {
            // 发送成功
            if (!error)
            {
                [self reloadMessage];
            }
        } onQueue:dispatch_get_main_queue()];
    }];
    [controller addAction:action];
    [controller addAction:action1];
    [controller addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
    }];
    [self presentViewController:controller animated:YES completion:nil];
}
- (void)didReceiveMessage:(EMMessage *)message
{
    [self reloadMessage];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.conversation.loadAllMessages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"CELL"];
    }
    // 每一个message表示一条聊天记录
    EMMessage *message = self.conversation.loadAllMessages[indexPath.row];
    // EMTextMessageBody 表示聊天的信息
    EMTextMessageBody *body = [message.messageBodies lastObject];
    // message.to 表示聊天的对象
    if ([message.to isEqualToString:self.chatter])
    {
        cell.textLabel.text = body.text;
        cell.detailTextLabel.text = @"";
    }
    else
    {
        cell.textLabel.text = @"";
        cell.detailTextLabel.text = body.text;
    }
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

--------------AddFriendsViewController.m-------------

#import "AddFriendsViewController.h"

#import <EaseMob.h>

@interface AddFriendsViewController ()

@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UIButton *addFriendsButton;

@end

@implementation AddFriendsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.userNameTextField.layer.borderWidth = 1;
    
}
- (IBAction)addFriendsButtonClicked:(id)sender
{
    EMError *error = nil;
    BOOL succeed = [[EaseMob sharedInstance].chatManager addBuddy:self.userNameTextField.text message:@"加一下好友,可以么?" error:&error];
    if (succeed && !error)
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        NSLog(@"error ==== %@", error);
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
Main.storyboard

工程截图
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、准备工作 1、注册环信帐号注册一个环信账号之后,我们用注册的帐号登陆。然后创建一个应用,会得到一个对应的App...
    niceSYT阅读 3,157评论 1 2
  • 一、准备工作 1、注册环信帐号 注册一个环信账号之后,我们用注册的帐号登陆。然后创建一个应用,会得到一个对应的Ap...
    樊二哈阅读 5,081评论 1 9
  • 第一次集成环信SDK应该是在去年吧,那个时候还是2.0的版本,没想到后面做的几个APP都用到了环信的及时聊天,用过...
    imGeek阅读 5,535评论 4 16
  • 版权声明:本文为博主原创文章,未经博主允许不得转载。 前言 公司最近要求做即时通讯, 直接用了三方环信了,今天和大...
    Heaven7th阅读 13,220评论 24 30
  • 柯特科本活着的时候我从未听过他的歌,在1997年敦煌音像出版社同时引进了never mind和Mtv不插电演唱会两...
    触摸音乐阅读 2,962评论 1 0

友情链接更多精彩内容