iOS开发OC -- 环信即时通讯的使用

一 环信简介

成立于2013年4月,是一家国内领先的企业级软件服务提供商,于2016年荣膺“Gartner 2016 Cool Vendor”。产品包括国内上线最早规模最大的即时通讯云平台——环信即时通讯云,以及移动端最佳实践的全媒体智能云客服平台——环信客户互动云。
相关链接

二 sdk集成

//集成环信SDK
pod 'Hyphenate',
//集成环信EaseUI
pod 'EaseUI', :git => 'https://github.com/easemob/easeui-ios-hyphenate-cocoapods.git', :tag => '3.3.2'
注意: 由于SDK改成了动态库,EaseUI引入的头文件Full版本和Lite版本不同,导致集成EaseUI失败。代码中包含了宏ENABLE_LITE的定义这个是为了区分集成Lite版本SDK还是Full版本SDK,当通过pod在集成EaseUILite时会在Build Settings> GCC_PREPROCESSOR_DEFINITIONS >ENABLE_LITE=1中定义ENABLE_LITE,集成EaseUI时则不会定义,所以开发者不需要关注这个字段,如果集成Lite版本SDK,建议使用
//集成环信Lite版SDK
pod 'HyphenateLite',
//集成环信EaseUI
pod 'EaseUILite', :git =>'https://github.com/easemob/easeui-ios-hyphenate-cocoapods.git', :tag => '3.3.2'

*总之 真的是会遇到很多坑 各种冲突什么的 EaseUI中含有第三方(MBProgressHUD、MJRefresh、MWPhotoBrowser、SDWebImage) 需要大家注意 我最后是物理集成EaseUI :( 其实我更喜欢pod

三 相关配置

制作上传证书用于消息推送

四 代码示例

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //环信相关集成
    //AppKey:注册的AppKey,详细见下面注释。
    //apnsCertName:推送证书名(不需要加后缀),详细见下面注释。
    
    EMOptions *options = [EMOptions optionsWithAppkey:@"1110170830178623#mengzhu"];
    options.apnsCertName = @"iosAppProCer";
    [[EMClient sharedClient] initializeSDKWithOptions:options];

    //EaseUI
    [[EaseSDKHelper shareHelper] hyphenateApplication:application
                        didFinishLaunchingWithOptions:launchOptions
                                               appkey:@"1110170830178623#mengzhu"
                                         apnsCertName:@"iosAppProCer"
                                          otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
    
    //环信推送
    EMPushOptions * pushOptions = [[EMClient sharedClient] pushOptions];
    //显示内容
    pushOptions.displayStyle = 1;
    //更新配置到服务器,该方法为同步方法,如果需要,请放到单独线程
    EMError *error = [[EMClient sharedClient] updatePushOptionsToServer];
    if(!error) {
        // 成功
    }else {
        // 失败
    }
    
    // 注册APNS离线推送  iOS8 注册APNS
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge |
        UIUserNotificationTypeSound |
        UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    else{
        UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeSound |
        UIRemoteNotificationTypeAlert;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];
    }
   
    // 设置应用程序的图标右上角的数字
    [application setApplicationIconBadgeNumber:0];

    //环信添加监听在线推送消息
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    return YES;
}

// APP进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}

// APP将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[EMClient sharedClient] applicationWillEnterForeground:application];
}

// 当掉线时,iOS SDK 会自动重连,只需要监听重连相关的回调,无需进行任何操作。
- (void)connectionStateDidChange:(EMConnectionState)aConnectionState
{
}
//注册环信
EMError *error = [[EMClient sharedClient] registerWithUsername:@"8001" password:@"111111"];
if (error==nil) {
    NSLog(@"注册成功");
}

//登录环信 登录一次就可以设置 自动登录了 所以要先判断一次
BOOL isAutoLogin = [EMClient sharedClient].options.isAutoLogin;
if (!isAutoLogin) {
    EMError *error = [[EMClient sharedClient] loginWithUsername:@"11236655" password:@"112233"];
          if (!error) {
               [[EMClient sharedClient].options setIsAutoLogin:YES];
              }
  }

//退出环信
EMError *error = [[EMClient sharedClient] logout:YES];
if (!error) {
    NSLog(@"环信退出成功");
 }

//环信相关  其他设备登录
- (void)userAccountDidLoginFromOtherDevice{}

//创建聊天 可以直接使用或者继承于EaseMessageViewController
//环信ID:@"8001"
//聊天类型:EMConversationTypeChat
EaseMessageViewController *chatController = [[EaseMessageViewController alloc] initWithConversationChatter:@"8001" conversationType:EMConversationTypeChat];

//环信消息推送处理
//注册和上传devicetoken
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    //环信注册通知
    [[EMClient sharedClient] bindDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSString *str = [NSString stringWithFormat: @"Error: %@",err];
    MZLog(@"%@",str);
}

//监听环信在线推送消息
- (void)messagesDidReceive:(NSArray *)aMessages{
    
    if (aMessages.count == 0) {
        return;
    }
    
    for (EMMessage * message in aMessages) {
        UIApplicationState state = [[UIApplication sharedApplication] applicationState];
        switch (state) {
                //前台运行
            case UIApplicationStateActive:
                [self showPushNotificationMessage:message];
                break;
                //待激活状态
            case UIApplicationStateInactive:
                [self showPushNotificationMessage:message];
                
                break;
                //后台运行
            case UIApplicationStateBackground:
                [self showPushNotificationMessage:message];
                break;
                
                
            default:
                break;
        }
    }

}

//监听环信之后  发送本地通知
- (void)showPushNotificationMessage:(EMMessage *)message{
    EMPushOptions *options = [[EMClient sharedClient] pushOptions];
    options.displayStyle = 1;
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date]; //触发通知的时间
    if (options.displayStyle == 1) {
        EMMessageBody *messageBody = message.body;
        NSString *messageStr = nil;
        switch (messageBody.type) {
            case 1:{
                messageStr = ((EMTextMessageBody *)messageBody).text;
            }
                break;
            case 2:{
                messageStr = @"发来一张图片";
            }
                break;
            case 4:{
                messageStr = @"发来ta的位置";
            }
                break;
            case 5:{
                messageStr = @"发来一段语音";
            }
                break;
            default:
                break;
        }
        
        notification.alertBody = [NSString stringWithFormat:@"%@",messageStr];
        notification.userInfo = @{@"msgtype":@(1),@"mid":message.messageId,@"f":message.from};
        notification.alertAction = NSLocalizedString(@"open", @"Open");
        notification.timeZone = [NSTimeZone defaultTimeZone];
        notification.repeatInterval = 0;
        notification.soundName= UILocalNotificationDefaultSoundName;
        //发送通知
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        
        UIApplication *application = [UIApplication sharedApplication];
        application.applicationIconBadgeNumber += 1;
    }
}

//本地通知点击事件
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    // 必须要监听--应用程序在后台的时候进行的跳转
    if (application.applicationState == UIApplicationStateInactive) {
        [self messageClickHandleWith:notification];
    }
}

//私信消息退推送点击事件
- (void)messageClickHandleWith:(UILocalNotification *)notification
{
    NSDictionary * dic = [notification userInfo];
    UIViewController * controller = [self getCurrentVC];
    MZOtherUserInfoModel * model = [MZOtherUserInfoModel new];
    model.uid = dic[@"mid"];
    model.nickname = dic[@"f"];
    MZMessageChatViewController * chat = [[MZMessageChatViewController alloc]initWithUserModel:model];
    [controller.navigationController pushViewController:chat animated:YES];
}

//获取当前controller
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal,如果不是,找到UIWindowLevelNormal的
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    id  nextResponder = nil;
    UIViewController *appRootVC=window.rootViewController;
    //    如果是present上来的appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }else{
        
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];
    }
    
    if ([nextResponder isKindOfClass:[UITabBarController class]]){
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        //        UINavigationController * nav = tabbar.selectedViewController ; 上下两种写法都行
        result=nav.childViewControllers.lastObject;
        
    }else if ([nextResponder isKindOfClass:[UINavigationController class]]){
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else{
        result = nextResponder;
    }
    return result;
}

//远程消息推送点击处理
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    if(userInfo)
    {
      //
    }
}

暂时先 粗略记载 后续有时间会细化:)

你可能感兴趣的:(iOS开发OC -- 环信即时通讯的使用)