快速入門(五分鐘運行環信demo)
下載環信demo (iOS)
什麼是環信demo
環信demo展示了怎樣使用環信SDK快速創建一個完整的類微信聊天APP。展示的功能包括:環信SDK初始化,登錄,登出,註冊消息接收listener, 發送消息。
環信demo源代碼已在github上開源供開發者下載,以幫助開發者更好的學習瞭解環信SDK。
下載環信demo
-
下載環信Demo及SDK: 下載
-
解壓縮iOSSDK.zip後會得到以下目錄結構:
運行環信demo (iOS)
在模擬器中運行chatdemo-nonui工程。
或者使用手機上的Safari瀏覽器訪問 www.easemob.com/downloads/chatdemo.html直接安裝
運行chatdemo-nonui:
點擊“發送文本消息”,會發送消息給測試機器人(其賬號爲”bot”)。該測試機器人接收到消息後會把接收的消息原封不動的自動發送回來,顯示如下圖。
快速集成
下載EaseMobSDK:
下載EaseMobSDK 下載鏈接
將EaseMobSDK拖入到項目中
SDK依賴庫
UIDemo依賴庫
設置Linker
向Other Linker Flags 中添加 -ObjC。(如果已有,則不需要再添加)
設置Architectures
初始化EaseMobSDK
在AppDelegate中註冊SDK
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
// 真機的情況下,notification提醒設置
UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];
//註冊 APNS文件的名字, 需要與後臺上傳證書時的名字一一對應
NSString *apnsCertName = @"chatdemo";
[[EaseMob sharedInstance] registerSDKWithAppKey:@"easemob-demo#chatdemo" apnsCertName:apnsCertName];
[[EaseMob sharedInstance] enableBackgroundReceiveMessage];
[[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
[self.window makeKeyAndVisible];
return YES;
}
關於EASEMOB_APPKEY,請登錄或註冊[環信開發者後臺(https://console.easemob.com),申請APPKEY後,進行相關配置。
從源代碼級別深入瞭解環信demo (iOS)
深入理解環信demo背後的代碼
註冊listener,以接收聊天消息:RootViewController.m
[[EaseMob sharedInstance].chatManager addDelegate:self
delegateQueue:nil];
登錄:見RandViewController+Login
[[EaseMob sharedInstance].chatManager asyncLoginWithUsername:username
password:@"123456"
completion:
^(NSDictionary *loginInfo, EMError *error) {
if (!error) {
NSLog(@"登錄成功");
}
} onQueue:nil];
退出登錄:見RandViewController+Login.m
[[EaseMob sharedInstance].chatManager asyncLogoff];
發送消息:見RootViewController+sendChat.m
EMChatText *text = [[EMChatText alloc] initWithText:message];
EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:text];
EMMessage *msg = [[EMMessage alloc]
initWithReceiver:@"bot"
bodies:[NSArray arrayWithObject:body]];
[[EaseMob sharedInstance].chatManager sendMessage:msg
progress:nil
error:nil];
接收聊天消息並顯示:見RootViewController.m
-(void)didReceiveMessage:(EMMessage *)message {
id body = [message.messageBodies firstObject];
if (body.messageBodyType == eMessageBodyType_Text) {
NSString *msg = ((EMTextMessageBody *)body).text;
NSLog(@"收到的消息---%@",msg);
}
}