iOS: 環信的推送

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

1.先建立一個apns證書,連接以下ios

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

  建立完證書後,將證書弄成p12文件,而後上傳到環信後臺async

2.再建立真機調試證書,和描述文件,保證能進行真機調試。而且appid要又推送功能ide

3.綁定環信證書和appkeyatom

//註冊 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;
}
這樣就能夠進行消息推送了

 

通過本身的研究,我的拓展一下:通常接收消息推送通知放在主控制器去操做,只須要在主控制器註冊代理,便可回調,發送通知spa

//**************************************************遠程通知部分*******************************************************//

//兩次提示的默認間隔.net

#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; }
相關文章
相關標籤/搜索