//
// SFTabBarController.h
// FootBath
//
// Created by zhang on 2016/12/13.
// Copyright © 2016年 zhang. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <EMClientDelegate.h>
@class EMMessage;
@interface SFTabBarController : UITabBarController
//设置未读信息
- (void)setupUnreadMessageCount;
//网络连接状态 发生变化(掉线, 在线)
- (void)networkChanged:(EMConnectionState)connectionState;
//收到消息 播放响铃
- (void)playSoundAndVibration;
//显示 通知
- (void)showNotificationWithMessage:(EMMessage *)message;
@end
//
// SFTabBarController.m
// FootBath
//
// Created by zhang on 2016/12/13.
// Copyright © 2016年 zhang. All rights reserved.
//
#import "SFTabBarController.h"
#import "SFHomeController.h"
#import "SFMessageController.h"
#import "SFMeController.h"
#import "CTMediator+Home.h"
#import "SFUserManager.h"
#import "EMCDDeviceManager.h"
#import "EaseSDKHelper.h"
#import <UserNotifications/UserNotifications.h>
#import "SFChatManager.h"
//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 3.0;
static NSString *kMessageType = @"MessageType";
static NSString *kConversationChatter = @"ConversationChatter";
static NSString *kGroupName = @"GroupName";
@interface SFTabBarController ()<UITabBarControllerDelegate>
@property (nonatomic,strong) NSArray *tabBarTitles;
@property (nonatomic,strong) NSArray *tabBarIcons;
@property (nonatomic,strong) NSArray *myControllers;
@property (nonatomic,strong) NSMutableArray *myNavgationViewControllers;
@property (strong, nonatomic) NSDate *lastPlaySoundDate;
@property (nonatomic,assign) EMConnectionState connectionState;
@end
@implementation SFTabBarController
- (void)viewDidLoad {
[super viewDidLoad];
[self configTabBarController];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)configTabBarController{
self.myNavgationViewControllers = [NSMutableArray array];
[self.myControllers enumerateObjectsUsingBlock:^(UIViewController *obj, NSUInteger idx, BOOL * _Nonnull stop) {
UITabBarItem *tabBarItem = [[UITabBarItem alloc] initWithTitle:nil image:[UIImage imageNamed:[NSString stringWithFormat:@"%@_normal", self.tabBarIcons[idx]]] selectedImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@_selected", self.tabBarIcons[idx]]]];
tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
UIViewController *vc = self.myControllers[idx];
vc.tabBarItem = tabBarItem;
[self.myNavgationViewControllers addObject:[[UINavigationController alloc] initWithRootViewController:vc]];
}];
self.tabBar.translucent = YES;
self.viewControllers = self.myNavgationViewControllers;
self.delegate = self;
//获取未读消息数,此时并没有把self注册为SDK的delegate,读取出的未读数是上次退出程序时的
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupUnreadMessageCount) name:@"setupUnreadMessageCount" object:nil];
}
#pragma mark - UITabBarControllerDelegate
#pragma mark -
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
static NSTimeInterval lastClickTime = 0;
UINavigationController *navgationController = (UINavigationController *)viewController;
//当选择 消息还有我的 的时候 在未登录的情况下 弹出登陆页(将要弹出的视图, 设置成Nav的RootVC 避免多层模态操作, 即模态到一个新的Nav)
if ((navgationController == self.viewControllers[1] || navgationController == self.viewControllers[2]) && ![SFUserManager sharedManager].hasLogin) {
UIViewController *vc = [[CTMediator sharedInstance] Home_loginController:nil];
[tabBarController.selectedViewController presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
return NO;
}
//处理tabBar双击
if (tabBarController.selectedViewController != viewController) {
lastClickTime = [NSDate timeIntervalSinceReferenceDate];
}
if (tabBarController.selectedViewController == viewController) {
NSTimeInterval clickTime = [NSDate timeIntervalSinceReferenceDate];
if (clickTime - lastClickTime <= 0.5 ) {
lastClickTime = clickTime;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
if ([navgationController.topViewController respondsToSelector:@selector(tabBarItemDoubleClicked)]) {
[navgationController.topViewController performSelector:@selector(tabBarItemDoubleClicked)];
}
#pragma clang diagnostic pop
return NO;
}
lastClickTime = clickTime;
//return NO;
}
return YES;
}
#pragma mark - getter and setter
#pragma mark -
- (NSArray *)tabBarTitles{
if (!_tabBarTitles) {
_tabBarTitles = @[@"", @"", @""];
}
return _tabBarTitles;
}
- (NSArray *)tabBarIcons{
if (!_tabBarIcons) {
_tabBarIcons = @[@"ic_tab_home", @"ic_tab_message", @"ic_tab_me"];
}
return _tabBarIcons;
}
- (NSArray *)myControllers{
if (!_myControllers) {
_myControllers = @[[SFHomeController new], [SFMessageController new], [SFMeController new]];
}
return _myControllers;
}
#pragma mark - public
#pragma mark -
// 统计未读消息数
-(void)setupUnreadMessageCount{
NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
NSInteger unreadCount = 0;
for (EMConversation *conversation in conversations) {
unreadCount += conversation.unreadMessagesCount;
}
SFMessageController *vc = self.myControllers[1];
if (vc) {
if (unreadCount > 0) {
vc.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
}else{
vc.tabBarItem.badgeValue = nil;
}
}
UIApplication *application = [UIApplication sharedApplication];
[application setApplicationIconBadgeNumber:unreadCount];
}
- (void)networkChanged:(EMConnectionState)connectionState{
_connectionState = connectionState;
SFMessageController *vc = self.myControllers[1];
[vc networkChanged:connectionState];
[SFChatManager sharedManager].conversationListVC = vc;
}
- (void)playSoundAndVibration{
NSTimeInterval timeInterval = [[NSDate date]
timeIntervalSinceDate:self.lastPlaySoundDate];
if (timeInterval < kDefaultPlaySoundInterval) {
//如果距离上次响铃和震动时间太短, 则跳过响铃
NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
return;
}
//保存最后一次响铃时间
self.lastPlaySoundDate = [NSDate date];
// 收到消息时,播放音频
[[EMCDDeviceManager sharedInstance] playNewMessageSound];
// 收到消息时,震动
[[EMCDDeviceManager sharedInstance] playVibration];
}
- (void)showNotificationWithMessage:(EMMessage *)message{
EMPushOptions *options = [[EMClient sharedClient] pushOptions];
NSString *alertBody = nil;
if (options.displayStyle == EMPushDisplayStyleMessageSummary) {
EMMessageBody *messageBody = message.body;
NSString *messageStr = nil;
switch (messageBody.type) {
case EMMessageBodyTypeText:
{
messageStr = ((EMTextMessageBody *)messageBody).text;
}
break;
case EMMessageBodyTypeImage:
{
messageStr = NSLocalizedString(@"message.image", @"Image");
}
break;
case EMMessageBodyTypeLocation:
{
messageStr = NSLocalizedString(@"message.location", @"Location");
}
break;
case EMMessageBodyTypeVoice:
{
messageStr = NSLocalizedString(@"message.voice", @"Voice");
}
break;
case EMMessageBodyTypeVideo:{
messageStr = NSLocalizedString(@"message.video", @"Video");
}
break;
default:
break;
}
do {
// NSString *title = [[UserProfileManager sharedInstance] getNickNameWithUsername:message.from];
NSString *title = message.from;;
if (message.chatType == EMChatTypeGroupChat) {
NSDictionary *ext = message.ext;
if (ext && ext[kGroupMessageAtList]) {
id target = ext[kGroupMessageAtList];
if ([target isKindOfClass:[NSString class]]) {
if ([kGroupMessageAtAll compare:target options:NSCaseInsensitiveSearch] == NSOrderedSame) {
alertBody = [NSString stringWithFormat:@"%@%@", title, NSLocalizedString(@"group.atPushTitle", @" @ me in the group")];
break;
}
}
else if ([target isKindOfClass:[NSArray class]]) {
NSArray *atTargets = (NSArray*)target;
if ([atTargets containsObject:[EMClient sharedClient].currentUsername]) {
alertBody = [NSString stringWithFormat:@"%@%@", title, NSLocalizedString(@"group.atPushTitle", @" @ me in the group")];
break;
}
}
}
NSArray *groupArray = [[EMClient sharedClient].groupManager getJoinedGroups];
for (EMGroup *group in groupArray) {
if ([group.groupId isEqualToString:message.conversationId]) {
title = [NSString stringWithFormat:@"%@(%@)", message.from, group.subject];
break;
}
}
}
else if (message.chatType == EMChatTypeChatRoom)
{
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSString *key = [NSString stringWithFormat:@"OnceJoinedChatrooms_%@", [[EMClient sharedClient] currentUsername]];
NSMutableDictionary *chatrooms = [NSMutableDictionary dictionaryWithDictionary:[ud objectForKey:key]];
NSString *chatroomName = [chatrooms objectForKey:message.conversationId];
if (chatroomName)
{
title = [NSString stringWithFormat:@"%@(%@)", message.from, chatroomName];
}
}
alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
} while (0);
}
else{
//alertBody = NSLocalizedString(@"receiveMessage", @"you have a new message");
alertBody = @"您有一条新消息";
}
NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];
BOOL playSound = NO;
if (!self.lastPlaySoundDate || timeInterval >= kDefaultPlaySoundInterval) {
self.lastPlaySoundDate = [NSDate date];
playSound = YES;
}
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setObject:[NSNumber numberWithInt:message.chatType] forKey:kMessageType];
[userInfo setObject:message.conversationId forKey:kConversationChatter];
//发送本地推送
if (NSClassFromString(@"UNUserNotificationCenter")) {
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.01 repeats:NO];
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
if (playSound) {
content.sound = [UNNotificationSound defaultSound];
}
content.body =alertBody;
content.userInfo = userInfo;
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:message.messageId content:content trigger:trigger];
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
}
else {
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate date]; //触发通知的时间
notification.alertBody = alertBody;
notification.alertAction = NSLocalizedString(@"open", @"Open");
notification.timeZone = [NSTimeZone defaultTimeZone];
if (playSound) {
notification.soundName = UILocalNotificationDefaultSoundName;
}
notification.userInfo = userInfo;
//发送通知
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
}
@end