iOS: 环信的推送

简介:

原文:http://m.blog.csdn.net/article/details?id=38824551

1.先创建一个apns证书,链接如下

  http://developer.easemob.com/docs/emchat/ios/push/certificate.html

  创建完证书后,将证书弄成p12文件,然后上传到环信后台

2.再创建真机调试证书,和描述文件,保证能进行真机调试。并且appid要又推送功能

3.绑定环信证书和appkey

//注册 APNS文件的名字, 需要与后台上传证书时的名字一一对应
NSString *apnsCertName = @"chatdemo";
[[EaseMob sharedInstance] registerSDKWithAppKey:@“4545521” apnsCertName:apnsCertName];
[[EaseMob sharedInstance] enableBackgroundReceiveMessage];
[[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
4.然后实现环信的几个方法
复制代码
// 收到消息回调
-(void)didReceiveMessage:(EMMessage *)message{
    
#if !TARGET_IPHONE_SIMULATOR
    [self playSoundAndVibration];
    
    BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
    if (!isAppActivity) {
        [self showNotificationWithMessage:message];
    }
#endif
}

- (void)playSoundAndVibration{
    
    //如果距离上次响铃和震动时间太短, 则跳过响铃
    NSLog(@"%@, %@", [NSDate date], self.lastPlaySoundDate);
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        return;
    }
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时,播放音频
    [[EaseMob sharedInstance].deviceManager asyncPlayNewMessageSound];
    // 收到消息时,震动
    [[EaseMob sharedInstance].deviceManager asyncPlayVibration];
}

- (void)showNotificationWithMessage:(EMMessage *)message{
    id<IEMMessageBody> messageBody = [message.messageBodies firstObject];
    NSString *messageStr = nil;
    switch (messageBody.messageBodyType) {
        case eMessageBodyType_Text:
        {
            messageStr = ((EMTextMessageBody *)messageBody).text;
        }
            break;
        case eMessageBodyType_Image:
        {
            messageStr = @"[图片]";
        }
            break;
        case eMessageBodyType_Location:
        {
            messageStr = @"[位置]";
        }
            break;
        case eMessageBodyType_Voice:
        {
            messageStr = @"[音频]";
        }
            break;
        case eMessageBodyType_Video:{
            messageStr = @"[视频]";
        }
            break;
        default:
            break;
    }
    
    //发送本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date]; //触发通知的时间
    
    NSString *title = message.from;
    if (message.isGroup) {
        NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
        for (EMGroup *group in groupArray) {
            if ([group.groupId isEqualToString:message.conversation.chatter]) {
                title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, group.groupSubject];
                break;
            }
        }
    }
    
    notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
    notification.alertAction = @"打开";
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.soundName = UILocalNotificationDefaultSoundName;

    //发送通知
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    UIApplication *application = [UIApplication sharedApplication];
    application.applicationIconBadgeNumber += 1;
}
复制代码
这样就可以进行消息推送了

 

经过自己的研究,个人拓展一下:一般接收消息推送通知放在主控制器去操作,只需要在主控制器注册代理,即可回调,发送通知

复制代码
//**************************************************远程通知部分*******************************************************//

//两次提示的默认间隔

#import "MainViewController.h"

static const CGFloat kDefaultPlaySoundInterval = 3.0;  

static NSString *kMessageType = @"MessageType";

static NSString *kConversationChatter = @"ConversationChatter";

 
  

@interface MainViewController ()<EMChatManagerChatDelegate>

@property (strong, nonatomic) NSDate *lastPlaySoundDate;

@end

 

#pragma - 远程通知部分

- (BOOL)needShowNotification:(NSString *)fromChatter
{
    BOOL ret = YES;
    NSArray *igGroupIds = [[EaseMob sharedInstance].chatManager ignoredGroupIds];
    for (NSString *str in igGroupIds) {
        if ([str isEqualToString:fromChatter]) {
            ret = NO;
            break;
        }
    }
    return ret;
}

// 收到消息回调
-(void)didReceiveMessage:(EMMessage *)message
{
    BOOL needShowNotification = (message.messageType != eMessageTypeChat) ? [self needShowNotification:message.conversationChatter] : YES;
    if (needShowNotification) {
#if !TARGET_IPHONE_SIMULATOR
        
        UIApplicationState state = [[UIApplication sharedApplication] applicationState];
        switch (state) {
            case UIApplicationStateActive:
                [self playSoundAndVibration];
                break;
            case UIApplicationStateInactive:
                [self playSoundAndVibration];
                break;
            case UIApplicationStateBackground:
                [self showNotificationWithMessage:message];
                break;
            default:
                break;
        }
#endif
    }
}

//透传消息
-(void)didReceiveCmdMessage:(EMMessage *)message { [self showHint:NSLocalizedString(@"receiveCmd", @"receive cmd message")]; } - (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 { EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions]; //发送本地推送 UILocalNotification *notification = [[UILocalNotification alloc] init]; notification.fireDate = [NSDate date]; //触发通知的时间 if (options.displayStyle == ePushNotificationDisplayStyle_messageSummary) { id<IEMMessageBody> messageBody = [message.messageBodies firstObject]; NSString *messageStr = nil; switch (messageBody.messageBodyType) { case eMessageBodyType_Text: { messageStr = ((EMTextMessageBody *)messageBody).text; } break; case eMessageBodyType_Image: { messageStr = NSLocalizedString(@"message.image", @"Image"); } break; case eMessageBodyType_Location: { messageStr = NSLocalizedString(@"message.location", @"Location"); } break; case eMessageBodyType_Voice: { messageStr = NSLocalizedString(@"message.voice", @"Voice"); } break; case eMessageBodyType_Video:{ messageStr = NSLocalizedString(@"message.video", @"Video"); } break; default: break; } // NSString *title = [[UserProfileManager sharedInstance] getNickNameWithUsername:message.from]; NSString *title = message.from; if (message.messageType == eMessageTypeGroupChat) { // NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList]; // for (EMGroup *group in groupArray) { // if ([group.groupId isEqualToString:message.conversationChatter]) { // title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, group.groupSubject]; // break; // } // } } else if (message.messageType == eMessageTypeChatRoom) { // NSUserDefaults *ud = [NSUserDefaults standardUserDefaults]; // NSString *key = [NSString stringWithFormat:@"OnceJoinedChatrooms_%@", [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:@"username" ]]; // NSMutableDictionary *chatrooms = [NSMutableDictionary dictionaryWithDictionary:[ud objectForKey:key]]; // NSString *chatroomName = [chatrooms objectForKey:message.conversationChatter]; // if (chatroomName) // { // title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, chatroomName]; // } } notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr]; } else{ notification.alertBody = NSLocalizedString(@"receiveMessage", @"you have a new message"); } #warning 去掉注释会显示[本地]开头, 方便在开发中区分是否为本地推送 // notification.alertBody = [[NSString alloc] initWithFormat:@"[本地]%@", notification.alertBody]; notification.alertAction = NSLocalizedString(@"open", @"Open"); notification.timeZone = [NSTimeZone defaultTimeZone]; NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate]; if (timeInterval < kDefaultPlaySoundInterval) { NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate); } else { notification.soundName = UILocalNotificationDefaultSoundName; self.lastPlaySoundDate = [NSDate date]; } NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; [userInfo setObject:[NSNumber numberWithInt:message.messageType] forKey:kMessageType]; [userInfo setObject:message.conversationChatter forKey:kConversationChatter]; notification.userInfo = userInfo; //发送通知 [[UIApplication sharedApplication] scheduleLocalNotification:notification]; UIApplication *application = [UIApplication sharedApplication]; application.applicationIconBadgeNumber += 1; }
复制代码

 

程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式!
本文转自当天真遇到现实博客园博客,原文链接:http://www.cnblogs.com/XYQ-208910/p/5447751.html ,如需转载请自行联系原作者
相关文章
|
iOS开发
IOS - iOS 12 的“隐式推送”功能怎么用?
IOS - iOS 12 的“隐式推送”功能怎么用?
327 0
IOS - iOS 12 的“隐式推送”功能怎么用?
|
传感器 iOS开发
iOS 14.2正式版推送,多项改进,建议更新
近日苹果推送了iOS/iPadOS 14.2的正式版,虽然更新包只有700多兆,但内容还是非常丰富的。
114 0
iOS 14.2正式版推送,多项改进,建议更新
|
开发工具 iOS开发 开发者
iOS13即将到来,iOS推送Device Token适配详解
关于提前适配iOS13 苹果推送DeviceToken的通知 随着苹果iOS13系统即将发布,个推提前推出DeviceToken适配方案,以确保新版本的兼容与APP推送服务的正常使用。iOS13的一个重要变化是"[deviceTokendescription]" 会受不同运行环境及系统的影响而发生变化,如果未及时做好适配工作,会导致SDK绑定到错误的DeviceToken,从而影响APN推送。
3516 0
|
开发工具 Android开发 iOS开发
搞定iOS推送SDK集成,看这篇文章就够了!
一次偶然的机会,公司的项目要用到推送,我自己本来就很懒,不愿意去弄整套APNS的流程,刚好之前跟朋友聊起过他们的产品中集成了个推的Android推送,说是体验还可以,那这次我就试一下他们的iOS推送。
3013 0
|
开发工具 iOS开发
iOS推送SDK集成对比
由于自己的app想要一个推送功能,又由于调用系统的方法集成太麻烦,所以想找一个推送的SDK来做。市面上可以实现该功能的SDK有多种,比如极光,信鸽,个推,MobPush(ShareSDK他们家的)。
2277 0
|
存储 iOS开发 数据格式
iOS刚进入后台接受推送、打开推送调转到相应的界面
刚进入后台的时候消息处理时候我用了本地推送!可以看我前边写的博客,怎么处理刚进入后台接收推送的案例,链接 /**  注释:打开推送的三种方式:-peter  1、apns的时候,结束进程退出后台:启动的时候可在 didFinishLaunchingWithOptions的launchOptions中...
1186 0