-------------------AppDelegate.m-------------------
#import "AppDelegate.h"
// 環(huán)信的頭文件
#import <EaseMob.h>
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 注冊環(huán)信SDK
// 第一個參數(shù) :APPkey 由應(yīng)用名字#公司的ID構(gòu)成
// 第二個參數(shù) :如果使用推送功能 則需要填推送證書的名字
[[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進(jìn)入后臺
- (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.
}
// 申請?zhí)幚頃r間
- (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];
}
// 獲取數(shù)據(jù) 獲取當(dāng)前用戶的會話列表
- (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 聊天消息中保存的消息體對象
// 獲取到最后一次發(fā)送的消息
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)
{
// 環(huán)信的錯誤類 相當(dāng)于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)
{
// 環(huán)信的錯誤類 相當(dāng)于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:@"發(fā)送消息" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
{
}];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"發(fā)送" 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]];
// 發(fā)送這條消息
[[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil prepare:^(EMMessage *message, EMError *error)
{
// 準(zhǔn)備發(fā)送
} onQueue:dispatch_get_main_queue() completion:^(EMMessage *message, EMError *error)
{
// 發(fā)送成功
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
工程截圖