先上效果圖:
說(shuō)說(shuō)需求:開(kāi)發(fā)一個(gè)可以進(jìn)行即時(shí)視頻聊天軟件.
-
最近比較忙,考完試回到公司就要做這個(gè)即時(shí)通信demo.本來(lái)是打算用xmpp協(xié)議來(lái)做視頻通信的,想了想要搞后臺(tái),還要搭建服務(wù)器.一開(kāi)始沒(méi)明白是怎么樣的一種形式.(現(xiàn)在想了想,其實(shí)就是自己寫(xiě)個(gè)服務(wù)器,然后放在服務(wù)器上而已了""腦袋被驢踢了).讓后問(wèn)boss服務(wù)器是我自己寫(xiě)還是怎樣?然后boss讓我先做個(gè)環(huán)信的demo,搞完再搞xmpp.
東西都下好了,打算下個(gè)星期再弄,想接觸xmpp的同學(xué)可以了解一下.
環(huán)信,什么鬼?
- 1.集成IOS SDK前的準(zhǔn)備工作:
(如果需要推送消息,則要到蘋(píng)果官網(wǎng)上制作證書(shū),再到環(huán)信后臺(tái)制作推送證書(shū).
詳細(xì)請(qǐng)看http://www.easemob.com/docs/ios/IOSSDKPrepare/#registerDeveloper)
注冊(cè)環(huán)信開(kāi)發(fā)者賬號(hào)并創(chuàng)建后臺(tái)應(yīng)用,
登陸地址:https://console.easemob.com/?comeFrom=easemobHome
注冊(cè)和登陸就不多說(shuō)了,只介紹創(chuàng)建應(yīng)用: 一般我們選擇開(kāi)放注冊(cè).
- 2.然后開(kāi)始創(chuàng)建工程:
下載環(huán)信Demo及SDK:http://www.easemob.com/sdk/
解壓縮iOSSDK.zip后會(huì)得到以下目錄結(jié)構(gòu):
將EaseMobSDK拖入到項(xiàng)目中,并添加SDK依賴庫(kù)
添加 以后,在AppDelegate中注冊(cè)SDK
- 2.然后開(kāi)始創(chuàng)建工程:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{//registerSDKWithAppKey:為應(yīng)用標(biāo)示,apnsCertName為推送證書(shū);(如果沒(méi)用推送證書(shū),這里可以隨便)
[[EaseMob sharedInstance] registerSDKWithAppKey:@"easemob-demo#chatdemo" apnsCertName:apnsCertName];
// 需要在注冊(cè)sdk后寫(xiě)上該方法
[[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
return YES;
}
3.下面我們開(kāi)始主要界面的詳解:
先上圖吧.(因?yàn)橐曨l通信需要兩臺(tái)真機(jī),而我只能和iPhone對(duì)模擬器,所以沒(méi)有視頻圖,但demo已經(jīng)過(guò)測(cè)試可以視頻聊天)
-
-
要進(jìn)行對(duì)話,必須先有用戶名,這樣才能讓對(duì)方找到你.(先注冊(cè),再登錄.退出(用于測(cè)試))
登錄頁(yè)面的代碼比較簡(jiǎn)單.
//異步注冊(cè)賬號(hào) [[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:name.text password:password.text withCompletion: ^(NSString *username, NSString *password, EMError *error) { if (!error) {//注冊(cè)成功,顯示馬上登錄 UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:@"注冊(cè)成功筹燕,請(qǐng)登陸" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; alert = nil; }else{ //輸出錯(cuò)誤信息. } } onQueue:nil];
-
//////////////////////////////////////////////////////////////////////
// //異步登錄賬號(hào)
[[EaseMob sharedInstance].chatManager asyncLoginWithUsername:name.text
password:password.text
completion:
^(NSDictionary *loginInfo, EMError *error) {
if (loginInfo && !error) {
//設(shè)置是否自動(dòng)登錄
[[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
// 舊數(shù)據(jù)轉(zhuǎn)換 (如果您的sdk是由2.1.2版本升級(jí)過(guò)來(lái)的到踏,需要家這句話)
[[EaseMob sharedInstance].chatManager importDataToNewDatabase];
//獲取數(shù)據(jù)庫(kù)中數(shù)據(jù)
[[EaseMob sharedInstance].chatManager loadDataFromDatabase];
//獲取群組列表
[[EaseMob sharedInstance].chatManager asyncFetchMyGroupsList];
#warning 開(kāi)始跳轉(zhuǎn),然后開(kāi)始聊天
NSLog(@"登錄成功");
TTAlertNoTitle(@"登錄成功");
[self thisToChatViewController];
//發(fā)送自動(dòng)登陸狀態(tài)通知
//[[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
}
else
{//輸出錯(cuò)誤信息.(太多,所以詳見(jiàn)demo)
}
} onQueue:nil];
```
- 2.登錄后,有挺多的控件,
- 1.返回鍵:點(diǎn)擊時(shí)會(huì)調(diào)用-(void)dealloc方法,用做登出操作.
- 2.UITextField: 你想要發(fā)送對(duì)象的名稱,例如8080(下面將用8080做例子).
- 3.send:建立一個(gè)與8080的會(huì)話.
- 4.cheak:用于測(cè)試(現(xiàn)在沒(méi)用了)
- 5.hehe黃色的lable: 當(dāng)有收到消息的時(shí)候,文字內(nèi)容就會(huì)發(fā)生改變,顯示還有多少條未讀信息.
-
6.最下面是UITableview,顯示會(huì)話聯(lián)系人.
首先要將代理設(shè)置好
[[EaseMob sharedInstance].chatManager removeDelegate:self];
//注冊(cè)為SDK的ChatManager的delegate
[[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
[[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
//最后一個(gè)為即時(shí)通訊的代理,(即時(shí)視頻,即時(shí)語(yǔ)音)
當(dāng)離開(kāi)這個(gè)頁(yè)面的時(shí)候,要講代理取消掉,不然會(huì)造成別的頁(yè)面接收不了消息.
[[EaseMob sharedInstance].chatManager removeDelegate:self];
[[EaseMob sharedInstance].callManager removeDelegate:self];
這樣以后,就可以使用代理方法來(lái)作一些事情了
1.接收消息
-(void)didReceiveMessage:(EMMessage *)message
2. 未讀消息數(shù)量變化回調(diào)
-(void)didUnreadMessagesCountChanged
3.實(shí)時(shí)通話狀態(tài)發(fā)生變化時(shí)的回調(diào),(如果沒(méi)有實(shí)現(xiàn)這個(gè)函數(shù),視頻聊天邀請(qǐng)就會(huì)接收不到.)
- (void)callSessionStatusChanged:(EMCallSession *)callSession changeReason:(EMCallStatusChangedReason)reason error:(EMError *)error
-
3.(已經(jīng)更新)因?yàn)槭莇emo,就先用UITextView來(lái)顯示對(duì)話,在UITextField中輸入文字,點(diǎn)擊send,即可發(fā)送,對(duì)方發(fā)送過(guò)來(lái)的內(nèi)容也可以看到.點(diǎn)擊視頻聊天,大概要等5-10s對(duì)方才能收到請(qǐng)求.
發(fā)送消息
-(void) send:(UIButton *)sender{
// conversation= [[EaseMob sharedInstance].chatManager conversationForChatter:@"ozxozx" conversationType:eConversationTypeChat];
EMChatText *txtChat = [[EMChatText alloc] initWithText:sendContext.text];
EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:txtChat];
// 生成message
EMMessage *message = [[EMMessage alloc] initWithReceiver:userName bodies:@[body]];
message.messageType = eMessageTypeChat;
EMError *error = nil;
id <IChatManager> chatManager = [[EaseMob sharedInstance] chatManager];
// [chatManager asyncResendMessage:message progress:nil];
[chatManager sendMessage:message progress:nil error:&error];
if (error) {
UIAlertView * a = [[UIAlertView alloc] initWithTitle:@"error" message:@"發(fā)送失敗" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil, nil];
[a show];
}else {
textview.text = [NSString stringWithFormat:@"%@\n\t\t\t\t\t我說(shuō):%@",textview.text,sendContext.text];
}
}
//從會(huì)話管理者中獲得當(dāng)前會(huì)話.并將會(huì)話內(nèi)容顯示到textview中
-(void) addtext{
//1.
EMConversation *conversation2 = [[EaseMob sharedInstance].chatManager conversationForChatter:userName conversationType:0] ;
NSString * context = @"";//用于制作對(duì)話框中的內(nèi)容.(現(xiàn)在還沒(méi)有分自己發(fā)送的還是別人發(fā)送的.)
NSArray * arrcon;
NSArray * arr;
long long timestamp = [[NSDate date] timeIntervalSince1970] * 1000 + 1;//制作時(shí)間戳
arr = [conversation2 loadAllMessages]; // 獲得內(nèi)存中所有的會(huì)話.
arrcon = [conversation2 loadNumbersOfMessages:10 before:timestamp]; //根據(jù)時(shí)間獲得5調(diào)會(huì)話. (時(shí)間戳作用:獲得timestamp這個(gè)時(shí)間以前的所有/5會(huì)話)
// 2.
for (EMMessage * hehe in arrcon) {
id<IEMMessageBody> messageBody = [hehe.messageBodies firstObject];
NSString *messageStr = nil;
//3.
messageStr = ((EMTextMessageBody *)messageBody).text;
// [context stringByAppendingFormat:@"%@",messageStr ];
if (![hehe.from isEqualToString:userName]) {//如果是自己發(fā)送的.
context = [NSString stringWithFormat:@"%@\n\t\t\t\t\t我說(shuō):%@",context,messageStr];
}else{
context = [NSString stringWithFormat:@"%@\n%@",context,messageStr];
}
}
textview.text = context;
}
1 .EMConversation *conversation2 :會(huì)話對(duì)象,里面裝著當(dāng)前對(duì)話的雙方的各種消息(EMMessage).
2 . EMMessage 消息.
一個(gè)message的內(nèi)容(對(duì)方發(fā)來(lái)的)
{"messageId":"83265683047055820","messageType":0,"from":"ozx8899","bodies":
["{\"type\":\"txt\",\"msg\":\"反對(duì)黨\"}"]
,"isAcked":true,"to":"ozxozx","timestamp":1436951601011,"requireEncryption":false}
3.((EMTextMessageBody *)messageBody)即為"bodies":["{\"type\":\"txt\",\"msg\":\"反對(duì)黨\"}"] 即:消息為文本,信息內(nèi)容為:反對(duì)黨
視頻聊天
-(void)openTheVideo:(UIButton *)btn{
BOOL isopen = [self canVideo];//判斷能否打開(kāi)攝像頭,(太多,詳見(jiàn)demo)
EMError *error = nil;
EMCallSession *callSession = nil;
if (!isopen) {
NSLog(@"不能打開(kāi)視頻");
return ;
}
//這里發(fā)送異步視頻請(qǐng)求
callSession = [[EaseMob sharedInstance].callManager asyncMakeVideoCall:userName timeout:50 error:&error];
//請(qǐng)求完以后,開(kāi)始做下面的
if (callSession && !error) {
[[EaseMob sharedInstance].callManager removeDelegate:self];
CallViewController *callController = [[CallViewController alloc] initWithSession:callSession isIncoming:NO];
callController.modalPresentationStyle = UIModalPresentationOverFullScreen;
[self presentViewController:callController animated:NO completion:nil];
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", @"error") message:error.description delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
[alertView show];
alertView = nil;
}
}
視頻聊天的代碼主要在CallViewController中.如果需要改變視頻通話時(shí)的界面,就要改此控制器中的布局內(nèi)容.
最要值得主要的是在dealloc函數(shù)中一定要加下面兩句
[[EaseMob sharedInstance].callManager removeDelegate:self];
[[NSNotificationCenter defaultCenter] postNotificationName:@"callControllerClose" object:nil];
1.注銷(xiāo)callManager的代理 2.通知消息中心,即時(shí)對(duì)話已經(jīng)完成了
如果沒(méi)有第二句,那么你的程序就只能進(jìn)行一次即時(shí)通訊.
并且要在CallViewController將要返回的控制器中加上函數(shù),注冊(cè)當(dāng)前控制器為callManager的代理.
- (void)callControllerClose:(NSNotification *)notification
{
[[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
}
如果開(kāi)發(fā)過(guò)程中遇到問(wèn)題,不妨看看是不是兩個(gè)主要的代理沒(méi)有設(shè)定好:
[EaseMob sharedInstance].chatManager ; //這是會(huì)話管理者,獲取該對(duì)象后, 可以做登錄馍管、聊天犬钢、加好友等操作
[EaseMob sharedInstance].callManager ;//這是即時(shí)通訊(語(yǔ)音聊天和視頻聊天)的管理者.
demo可以在:https://github.com/ouzhenxuan/huanxinDemo 下載
使用前,請(qǐng)到http://www.easemob.com/downloads 把iOS版的SDK下載到工程中,即可使用
簡(jiǎn)化版的demo:https://github.com/ouzhenxuan/shipinchat
如果感覺(jué)對(duì)你有幫助,請(qǐng)點(diǎn)個(gè)star.最近十分需要.你的star是我工作的支持.