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