ios ~ 推送通知(阿里:集成AlicloudPush)

先来说一说我们之前公司的要求:
  • 之前,公司产品要求:
    (1)在一场比赛中,玩家加入、退出、比赛结束,等等事件发生时,及时刷新比赛页面的数据(之前我们使用的轮询,但影响设备性能,现已弃用);
    (2)在其他页面,当邀请该用户参加比赛、或其他情况时,顶部弹出通知,告知:”xxx邀请您参加****比赛“,点击该条通知,进行跳页;

一、准备工作,阿里官方文档:iOS 配置推送证书指南,先将推送证书配置好,并上传证书到移动推送控制台

测试阿里推送控制台https://next.api.aliyun.com/api/Push/2016-08-01/PushNoticeToiOS,输入各个信息,点击发起调用按钮即可。

  • 问题:Ad Hoc App如何进行生产环境推送通知测试?
    因为,Xcode直接安装到真机的app时开发环境下的app,其推送也是开发环境的推送。要想模拟App Store下载的app推送,就要专门打一个生产环境的包,
    这个问题:解决办法:官方文档
    第一步:
    使用正常的打包方式,archiive之后,点击Distribute App之后,选择如图,第二个按钮Ad Hoc,
生产环境: 开发环境:
生产环境.png
开发环境.png
20191127191533759.png
  • 第二步:
    一直点击next按钮,直到最后export按钮出来后,
    导出项目到桌面,然后把ipa包上传蒲公英平台,就可以正常测试生产环境推送了。😄😄

二、代码:下面的准备工作完成之后,就是使用了:(接受到消息的时候,或跳页、或刷新页面)


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //push 刷新消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadMatch) name:@"PUSH_MATCH_PERSON_CHANGE" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadMatch) name:@"FastScoringReloadMatch" object:nil];
}

1、准备工作:
// CocoaPods导入阿里推送
pod 'AlicloudPush'
// 在PCH文件、AppDelegate,或使用到的地方导入头文件
#import "GWPushManage.h"
2、在AppDelegate文件:
@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // 注册推送 
    [[GWPushManage sharedPushManage] registerPushWithApplication:application didFinishLaunchingWithOptions:launchOptions];

    return YES;
}

/// DeviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;
{
    [[GWPushManage sharedPushManage] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"推送Error");
    [[GWPushManage sharedPushManage] application:application didFailToRegisterForRemoteNotificationsWithError:error];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    // 静默推送:处理推送唤醒的功能
    [[GWPushManage sharedPushManage] application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

@end

在账号登录时,(1)在登录页面登录成功之后,注意:绑定账户,(2)或者,已登录时,在首页绑定账户
[[GWPushManage sharedPushManage] bindAccount:[NSString stringWithFormat:@"%ld",model.userId] withCallback:^(CloudPushCallbackResult *res) {
    NSLog(@"push log  绑定账户成功");
}];
退出时:解绑账户
[[GWPushManage sharedPushManage] unbindAccount:^(CloudPushCallbackResult *res) {
    NSLog(@"push log  注销登录解绑账户");
}];
3、封装:
GWPushManage.h
#import <Foundation/Foundation.h>
#import <UserNotifications/UserNotifications.h>
#import <CloudPushSDK/CloudPushSDK.h>

NS_ASSUME_NONNULL_BEGIN

@interface GWPushManage : NSObject

+ (instancetype)sharedPushManage;

/// 初始化推送
- (void)registerPushWithApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;

/// APNs注册成功回调,将返回的deviceToken上传到CloudPush服务器
/// DeviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;

/// APNs注册失败回调
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;

/// 静默推送:处理推送唤醒的功能
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler;

/**
 *  主动获取设备通知是否授权(iOS 10+)
 */
- (void)getNotificationSettingStatus:(void(^)(BOOL status))statusBlock;

/**
 *    获取本机的deviceId (deviceId为推送系统的设备标识)
 *
 *    @return deviceId
 */
- (NSString *)getDeviceId;

/**
 *    获取APNs返回的deviceToken
 *
 *    @return deviceToken
 */
- (NSString *)getApnsDeviceToken;

/**
 *    绑定账号
 *
 *    @param     account     账号名
 *    @param     callback    回调
 */
- (void)bindAccount:(NSString *)account
       withCallback:(CallbackHandler)callback;

/**
 *    解绑账号
 *
 *    @param     callback    回调
 */
- (void)unbindAccount:(CallbackHandler)callback;


@end

NS_ASSUME_NONNULL_END

GWPushManage.m
#import "GWPushManage.h"
#import "GWPushModel.h"

#import "GWFastScoringDetailVC.h"
#import "GWCSM_LaunchMatchDetailCTRL.h"
#import "GWGameReportCardVC.h"
#import "GWActualMatchController.h"

@interface GWPushManage ()<UNUserNotificationCenterDelegate>

@end

@implementation GWPushManage{
    // iOS 10通知中心
    UNUserNotificationCenter *_notificationCenter;
}


static GWPushManage *pushManage;

+ (instancetype)sharedPushManage {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        pushManage = [[self alloc] init];
    });
    return pushManage;
}

- (void)registerPushWithApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // APNs注册,获取deviceToken并上报
    [self registerAPNS:application];
    // 初始化SDK
    [self initCloudPush];
    // 监听推送通道打开动作
    [self listenerOnChannelOpened];
    // 监听推送消息到达
    [self registerMessageReceive];
    // 点击通知将App从关闭状态启动时,将通知打开回执上报
    [CloudPushSDK sendNotificationAck:launchOptions];
    
}

- (void)pushWithTitle:(NSString *)title body:(NSString *)body userInfo:(NSDictionary *)userInfo{
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.badge = [NSNumber numberWithInt:1];
    content.title = title;
//    content.subtitle = @"测试开始";
    content.body = body;
    content.userInfo = userInfo;
    content.sound = [UNNotificationSound defaultSound];
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:NO];
    UNNotificationRequest *notificationRequest = [UNNotificationRequest requestWithIdentifier:@"request1" content:content trigger:trigger];
    [center addNotificationRequest:notificationRequest withCompletionHandler:^(NSError * _Nullable error) {
    }];
}

#pragma mark APNs Register
/**
 *    向APNs注册,获取deviceToken用于推送
 */
- (void)registerAPNS:(UIApplication *)application {
    float systemVersionNum = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (systemVersionNum >= 10.0) {
        // iOS 10 notifications
        _notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
        // 创建category,并注册到通知中心
        [self createCustomNotificationCategory];
        _notificationCenter.delegate = self;
        // 请求推送权限
        [_notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                // granted
                NSLog(@"push log    开始注册push");
                // 向APNs注册,获取deviceToken
                dispatch_async(dispatch_get_main_queue(), ^{
                    [application registerForRemoteNotifications];
                });
            } else {
                // not granted
                NSLog(@"push log    用户拒绝通知权限");
            }
        }];
    } else if (systemVersionNum >= 8.0) {
        // iOS 8 Notifications
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
        [application registerUserNotificationSettings:
         [UIUserNotificationSettings settingsForTypes:
          (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                           categories:nil]];
        [application registerForRemoteNotifications];
#pragma clang diagnostic pop
    } else {
        // iOS < 8 Notifications
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
#pragma clang diagnostic pop
    }
}

/**
 *  主动获取设备通知是否授权(iOS 10+)
 */
- (void)getNotificationSettingStatus:(void(^)(BOOL status))statusBlock {
    [_notificationCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
            NSLog(@"push log    用户身份验证");
            statusBlock(YES);
        } else {
            NSLog(@"push log    用户拒绝");
            statusBlock(NO);
        }
    }];
}

/*
 *  APNs注册成功回调,将返回的deviceToken上传到CloudPush服务器
 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"push log    上传deviceToken到CloudPush服务器。");
    [CloudPushSDK registerDevice:deviceToken withCallback:^(CloudPushCallbackResult *res) {
        if (res.success) {
            NSLog(@"push log    注册 deviceToken 成功, deviceToken: %@", [CloudPushSDK getApnsDeviceToken]);
        } else {
            NSLog(@"push log    注册 deviceToken 失败, error: %@", res.error);
        }
    }];
}

/*
 *  APNs注册失败回调
 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"push log    APNS注册失败 %@", error);
}

/**
 *  创建并注册通知category(iOS 10+)
 */
- (void)createCustomNotificationCategory {
    // 自定义`action1`和`action2`
    UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action1" title:@"test1" options: UNNotificationActionOptionNone];
    UNNotificationAction *action2 = [UNNotificationAction actionWithIdentifier:@"action2" title:@"test2" options: UNNotificationActionOptionNone];
    // 创建id为`test_category`的category,并注册两个action到category
    // UNNotificationCategoryOptionCustomDismissAction表明可以触发通知的dismiss回调
    UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"test_category" actions:@[action1, action2] intentIdentifiers:@[] options:
                                        UNNotificationCategoryOptionCustomDismissAction];
    // 注册category到通知中心
    [_notificationCenter setNotificationCategories:[NSSet setWithObjects:category, nil]];
}

/**
 *  处理iOS 10通知(iOS 10+)
 */
- (void)handleiOS10Notification:(UNNotification *)notification {
    UNNotificationRequest *request = notification.request;
    UNNotificationContent *content = request.content;
    NSDictionary *userInfo = content.userInfo;
    // 通知时间
    NSDate *noticeDate = notification.date;
    // 标题
    NSString *title = content.title;
    // 副标题
    NSString *subtitle = content.subtitle;
    // 内容
    NSString *body = content.body;
    // 角标
    int badge = [content.badge intValue];
    // 取得通知自定义字段内容,例:获取key为"Extras"的内容
    NSString *extras = [userInfo valueForKey:@"Extras"];
    // 通知角标数清0
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    // 同步角标数到服务端
//     [self syncBadgeNum:0];
    // 通知打开回执上报
    [CloudPushSDK sendNotificationAck:userInfo];
    
//    [self pushWithTitle:title body:body userInfo:userInfo];
    NSLog(@"push log    推送内容, 日期: \n%@\n, 标题: \n%@\n, 子标题: \n%@\n, 包: \n%@\n, 角标: %d\n, 拓展: %@.\n", noticeDate, title, subtitle, body, badge, extras);
}

/**
 *  App处于前台时收到通知(iOS 10+),收到推送通知之后调用,completionHandler回调可以控制是否显示alert、badge和sound。
 */
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSLog(@"Receive a notification in foregound.");
    // 处理iOS 10通知相关字段信息
    [self handleiOS10Notification:notification];
    // 通知不弹出
    //completionHandler(UNNotificationPresentationOptionNone);
    // 通知弹出,且带有声音、内容和角标(App处于前台时不建议弹出通知)
    completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}

/**
 *  触发通知动作时回调,比如点击、删除通知和点击自定义action(iOS 10+)
 *  (主要是当App在后台以及关闭状态下收到通知之后通过点击通知打开App的时候调用。当然,前台也可以点击使用)
 */
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    NSString *userAction = response.actionIdentifier;
    // 点击通知打开
    if ([userAction isEqualToString:UNNotificationDefaultActionIdentifier]) {
        NSLog(@"push log    点击推送");
        
        UNNotification *notification = response.notification;
        UNNotificationRequest *request = notification.request;
        UNNotificationContent *content = request.content;
        NSDictionary *userInfo = content.userInfo;

        // 取得通知自定义字段内容,例:获取key为"Extras"的内容
        NSString *extras = [userInfo valueForKey:@"Extras"];
        GWPushModel *pushModel = [GWPushModel modelWithDictionary:userInfo];
        
        [self didPush:pushModel];
        
        // 处理iOS 10通知,并上报通知打开回执
        [self handleiOS10Notification:response.notification];
    }
    // 通知dismiss,category创建时传入UNNotificationCategoryOptionCustomDismissAction才可以触发
    if ([userAction isEqualToString:UNNotificationDismissActionIdentifier]) {
        [CloudPushSDK sendDeleteNotificationAck:response.notification.request.content.userInfo];
    }
    completionHandler();
}

#pragma mark SDK Init
- (void)initCloudPush {
    
#ifdef DEBUG
    // 正式上线建议关闭
    [CloudPushSDK turnOnDebug];
    NSLog(@"push log    Push 通道=%d",[CloudPushSDK isChannelOpened]);
    
#else

#endif
    
    // SDK初始化,无需输入配置信息
    // 请从控制台下载AliyunEmasServices-Info.plist配置文件,并正确拖入工程
    [CloudPushSDK autoInit:^(CloudPushCallbackResult *res) {
        if (res.success) {
            NSLog(@"push log    Push SDK 注册成功, deviceId: %@.", [CloudPushSDK getDeviceId]);
        } else {
            NSLog(@"push log    Push SDK init 注册失败, error: %@", res.error);
        }
    }];
}

#pragma mark Notification Open
/*
 *  App处于启动状态时,通知打开回调
 */
//- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo {
//    NSLog(@"push log    收到新的push");
//    // 取得APNS通知内容
//    NSDictionary *aps = [userInfo valueForKey:@"aps"];
//    // 内容
//    NSString *content = [aps valueForKey:@"alert"];
//    // badge数量
//    NSInteger badge = [[aps valueForKey:@"badge"] integerValue];
//    // 播放声音
//    NSString *sound = [aps valueForKey:@"sound"];
//    // 取得通知自定义字段内容,例:获取key为"Extras"的内容
//    NSString *extras = [userInfo valueForKey:@"Extras"]; //服务端中Extras字段,key是自己定义的
//    NSLog(@"push log    推送内容, 内容: \n%@\n, 播放什么声音: \n%@\n, 角标: %ld\n, 拓展: %@.\n", content, sound, badge, extras);
//
//    // iOS badge 清0
//    application.applicationIconBadgeNumber = 0;
//    // 同步通知角标数到服务端
//    // [self syncBadgeNum:0];
//    // 通知打开回执上报
//    // [CloudPushSDK handleReceiveRemoteNotification:userInfo];(Deprecated from v1.8.1)
//    [CloudPushSDK sendNotificationAck:userInfo];
//}

/*
 * 方法application:didReceiveRemoteNotification:已废弃,只用下面👇🏻这个方法
 *  App处于启动状态时,通知打开回调 ()
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    // 静默推送:处理推送唤醒的功能
    
    NSLog(@"push log    收到新的push");
    // 取得APNS通知内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    // 内容
    NSString *content = [aps valueForKey:@"alert"];
    // badge数量
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue];
    // 播放声音
    NSString *sound = [aps valueForKey:@"sound"];
    // 取得通知自定义字段内容,例:获取key为"Extras"的内容
    NSString *extras = [userInfo valueForKey:@"Extras"]; //服务端中Extras字段,key是自己定义的
    NSLog(@"push log    推送内容, 内容: \n%@\n, 播放什么声音: \n%@\n, 角标: %ld\n, 拓展: %@.\n", content, sound, badge, extras);
    
    // iOS badge 清0
    application.applicationIconBadgeNumber = 0;
    // 同步通知角标数到服务端
    // [self syncBadgeNum:0];
    // 通知打开回执上报
    // [CloudPushSDK handleReceiveRemoteNotification:userInfo];(Deprecated from v1.8.1)
    [CloudPushSDK sendNotificationAck:userInfo];
}

#pragma mark Channel Opened
/**
 *    注册推送通道打开监听
 */
- (void)listenerOnChannelOpened {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onChannelOpened:)
                                                 name:@"CCPDidChannelConnectedSuccess"
                                               object:nil];
}

/**
 *    推送通道打开回调
 */
- (void)onChannelOpened:(NSNotification *)notification {
    
    NSLog(@"push log  消息通道建立成功");
    
//#ifdef DEBUG
//    [LCM_AlertViewFactory showAlterControllerWithTitle:@"温馨提示" message:@"消息通道建立成功" leftButtonTitle:@"已阅" rightButtonTitle:@"" leftButtonAction:^{
//
//    } rightButtonAction:^{
//
//    }];
//#else
//
//#endif
    
}

#pragma mark Receive Message
/**
 *    @brief    注册推送消息到来监听
 */
- (void)registerMessageReceive {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onMessageReceived:)
                                                 name:@"CCPDidReceiveMessageNotification"
                                               object:nil];
}

/**
 *    处理到来推送消息
 */
- (void)onMessageReceived:(NSNotification *)notification {
    NSLog(@"push log    接收一个消息!");
   
    CCPSysMessage *message = [notification object];
    NSString *title = [[NSString alloc] initWithData:message.title encoding:NSUTF8StringEncoding];
    NSString *body = [[NSString alloc] initWithData:message.body encoding:NSUTF8StringEncoding];
    NSLog(@"push log    收到消息的title: %@, content: %@.", title, body);
    
    GWPushModel *pushModel = [GWPushModel modelWithJSON:message.body];
    
    [self reloadPushWithModel:pushModel];
}

/* 同步通知角标数到服务端 */
- (void)syncBadgeNum:(NSUInteger)badgeNum {
    [CloudPushSDK syncBadgeNum:badgeNum withCallback:^(CloudPushCallbackResult *res) {
        if (res.success) {
            NSLog(@"push log    同步角标数量: [%lu] success.", (unsigned long)badgeNum);
        } else {
            NSLog(@"push log    同步角标数量: [%lu] failed, error: %@", (unsigned long)badgeNum, res.error);
        }
    }];
}

- (void)applicationWillTerminate:(UIApplication *)application {

}

/**
 *    获取本机的deviceId (deviceId为推送系统的设备标识)
 *
 *    @return deviceId
 */
- (NSString *)getDeviceId;
{
    return [CloudPushSDK getDeviceId];
}

/**
 *    获取APNs返回的deviceToken
 *
 *    @return deviceToken
 */
- (NSString *)getApnsDeviceToken;
{
    return [CloudPushSDK getApnsDeviceToken];
}

/**
 *    绑定账号
 *
 *    @param     account     账号名
 *    @param     callback    回调
 */
- (void)bindAccount:(NSString *)account
       withCallback:(CallbackHandler)callback;
{
#ifdef DEBUG
    
        NSString *aaccount = [NSString stringWithFormat:@"debug_%@",account];
#else
    // Release模式的代码...
        NSString *aaccount = [NSString stringWithFormat:@"release_%@",account];
#endif
    
    [CloudPushSDK bindAccount:aaccount withCallback:callback];
}

/**
 *    解绑账号
 *
 *    @param     callback    回调
 */
- (void)unbindAccount:(CallbackHandler)callback;
{
    [CloudPushSDK unbindAccount:callback];
}

#pragma mark  --  收到消息
- (void)reloadPushWithModel:(GWPushModel *)pushModel
{
    if (pushModel.type == NEW_MESSAGE) {// 消息列表新消息
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PUSH_NEW_MESSAGE" object:nil];
    } else if (pushModel.type == MATCH_PERSON_CHANGE ){// 约球球员增删改
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PUSH_MATCH_PERSON_CHANGE" object:nil];
    } else if (pushModel.type == TEAM_MATCH_PERSON_CHANGE ){// 球队赛球员增删改
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PUSH_TEAM_MATCH_PERSON_CHANGE" object:nil];
    } else if (pushModel.type == TEAM_MATCH_STATUS_CHANGE ){// 比赛按钮状态改变
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PUSH_TEAM_MATCH_STATUS_CHANGE" object:nil];
    } else if (pushModel.type == NEW_TEAM_MATCH_APPLY ){// 比赛申请列表更新
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PUSH_NEW_TEAM_MATCH_APPLY" object:nil];
    } else if (pushModel.type == NEW_TEAM_APPLY ){// 球队申请列表更新
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PUSH_NEW_TEAM_APPLY" object:nil];
    } else if (pushModel.type == TEAM_PERSON_CHANGE ){// 球队队员增删改
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PUSH_TEAM_PERSON_CHANGE" object:nil];
    } else if (pushModel.type == NEW_FRIEND_APPLY ){// 新增好友申请
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PUSH_NEW_FRIEND_APPLY" object:nil];
    } else if (pushModel.type == FRIEND_LIST_CHANGE ){// 好友列表增删改
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PUSH_FRIEND_LIST_CHANGE" object:nil];
    }
}

#pragma mark  --  点击推送跳转
- (void)didPush:(GWPushModel *)pushModel{
    // 获取当前VC
    UIViewController *controller = [LCM_Tool getCurrentVCFrom:UIApplication.sharedApplication.keyWindow.rootViewController];
    
    if ([NSStringFromClass([controller class]) isEqualToString:@"GWStartPageAnimationCRTL"]) { // 启动页展示的时间2秒,展现启动页之后,在获取当前页
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            UIViewController *VC = [LCM_Tool getCurrentVCFrom:UIApplication.sharedApplication.keyWindow.rootViewController];
            [self didPushTo:pushModel controller:VC];
        });
        
    }else{
        [self didPushTo:pushModel controller:controller];
    }
}


- (void)didPushTo:(GWPushModel *)pushModel controller:(UIViewController *)controller{
    if (pushModel.type == JOIN_MATCH){//被动/扫码加入比赛
        
    }else if (pushModel.type == APPLY_JOIN_MATCH_SUCCESS){//比赛报名成功(审核通过)
        if (pushModel.matchMode == 100) {
            [self pushToFastScoringDetailWithMatchId:pushModel.matchId withController:controller];
        }else{
            [self pushToGWCSM_LaunchMatchDetailCTRLWithMatchId:pushModel.matchId withController:controller];
        }
    }else if (pushModel.type == MATCH_START_SOON){//比赛快开始
        if (pushModel.matchMode == 100) {
            [self pushToFastScoringDetailWithMatchId:pushModel.matchId withController:controller];
        }else{
            [self pushToGWCSM_LaunchMatchDetailCTRLWithMatchId:pushModel.matchId withController:controller];
        }
    }else if (pushModel.type == MATCH_START){//球队赛/约球比赛开始
        [self pushToGWActualMatchControllerWithMatchId:pushModel.matchId withController:controller];
    }else if (pushModel.type == MATCH_AUTO_END){//比赛自动结束
        [self pushToGWCSM_LaunchMatchDetailWithMatchId:pushModel.matchId withController:controller];
    }
}

#pragma mark  --  跳转快速计分详情
- (void)pushToFastScoringDetailWithMatchId:(NSInteger)matchId withController:(UIViewController *)controller{
    if ([[controller class] isKindOfClass:[GWFastScoringDetailVC class]]) {
        GWFastScoringDetailVC *ctrl = (GWFastScoringDetailVC *)controller;
        if ([ctrl.matchId integerValue] == matchId) {
            //同一个控制器 不需要跳转
            return;
        }
    }

    GWFastScoringDetailVC *launchMatchDetailVC = [[GWFastScoringDetailVC alloc] init];
    launchMatchDetailVC.matchId = [NSString stringWithFormat:@"%ld",matchId];
    [controller.navigationController pushViewController:launchMatchDetailVC animated:YES];

}

#pragma mark  --  跳转成绩单
- (void)pushToGWCSM_LaunchMatchDetailWithMatchId:(NSInteger)matchId withController:(UIViewController *)controller{
    if ([[controller class] isKindOfClass:[GWGameReportCardVC class]]) {
        GWGameReportCardVC *ctrl = (GWGameReportCardVC *)controller;
        if (ctrl.matchId == matchId) {
            //同一个控制器 不需要跳转
            return;
        }
    }

    GWGameReportCardVC *launchMatchDetailVC = [[GWGameReportCardVC alloc] init:matchId];
    [controller.navigationController pushViewController:launchMatchDetailVC animated:YES];

}


#pragma mark  --  跳转比赛详情
- (void)pushToGWCSM_LaunchMatchDetailCTRLWithMatchId:(NSInteger)matchId withController:(UIViewController *)controller{
    if ([[controller class] isKindOfClass:[GWCSM_LaunchMatchDetailCTRL class]]) {
        GWCSM_LaunchMatchDetailCTRL *ctrl = (GWCSM_LaunchMatchDetailCTRL *)controller;
        if ([ctrl.matchID integerValue] == matchId) {
            //同一个控制器 不需要跳转
            return;
        }
    }

    GWCSM_LaunchMatchDetailCTRL *launchMatchDetailVC = [[GWCSM_LaunchMatchDetailCTRL alloc] init];
    launchMatchDetailVC.matchID = [NSString stringWithFormat:@"%ld",matchId];
    [controller.navigationController pushViewController:launchMatchDetailVC animated:YES];

}

#pragma mark  --  跳转比赛详情
- (void)pushToGWActualMatchControllerWithMatchId:(NSInteger)matchId withController:(UIViewController *)controller{
    if ([[controller class] isKindOfClass:[GWActualMatchController class]]) {
        GWActualMatchController *ctrl = (GWActualMatchController *)controller;
        if (ctrl.matchId == matchId) {
            //同一个控制器 不需要跳转
            return;
        }
    }

    GWActualMatchController *vc = [[GWActualMatchController alloc] initWithMatchId:matchId];
    [controller.navigationController pushViewController:vc animated:YES];

}

@end

4、自定义一个消息类型的Model:GWPushModel
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN
//推送 
//    /**
//     * 被动/扫码加入比赛
//     */
//    JOIN_MATCH(1, "NOTICE", "${userName}", "已成功约您'${courtName}'打球,记得来参加~"),
//    /**
//     * 比赛报名成功(审核通过)
//     */
//    APPLY_JOIN_MATCH_SUCCESS(2, "NOTICE", "参赛成功", "您报名的'${matchName}'已通过审核,请按时参加"),
//    /**
//     * 比赛快开始
//     */
//    MATCH_START_SOON(3, "NOTICE", "日程提醒", "您参加的'${matchName}'明天开始,提前做好行程规划哦~"),
//    /**
//     * 球队赛/约球比赛开始
//     */
//    MATCH_START(4, "NOTICE", "开球提示", "您参加的'${matchName}'已开始,快去计分吧"),
//    /**
//     * 比赛自动结束
//     */
//    MATCH_AUTO_END(14, "NOTICE", "计分结束", "您参加的'${matchName}'已自动结束,可在历史记录中查看计分详情"),
//消息
    /**
     * 消息列表新消息
     */
//    NEW_MESSAGE(5, "MESSAGE", "消息中心", ""),
//    /**
//     * 约球球员增删改
//     */
//    MATCH_PERSON_CHANGE(6, "MESSAGE", "约球模块更新", ""),
//    /**
//     * 球队赛球员增删改
//     */
//    TEAM_MATCH_PERSON_CHANGE(7, "MESSAGE", "球队赛模块更新", ""),
//    /**
//     * 比赛按钮状态改变
//     */
//    TEAM_MATCH_STATUS_CHANGE(8, "MESSAGE", "比赛详情", ""),
//    /**
//     * 比赛申请列表更新
//     */
//    NEW_TEAM_MATCH_APPLY(9, "MESSAGE", "赛事管理", ""),
//    /**
//     * 球队申请列表更新
//     */
//    NEW_TEAM_APPLY(10, "MESSAGE", "球队详情", ""),
//    /**
//     * 球队队员增删改
//     */
//    TEAM_PERSON_CHANGE(11, "MESSAGE", "球队管理", ""),
//    /**
//     * 新增好友申请
//     */
//    NEW_FRIEND_APPLY(12, "MESSAGE", "好友申请", ""),
//    /**
//     * 好友列表增删改
//     */
//    FRIEND_LIST_CHANGE(13, "MESSAGE", "我的好友", "");
typedef enum {
    JOIN_MATCH = 1, //被动/扫码加入比赛
    APPLY_JOIN_MATCH_SUCCESS = 2, //比赛报名成功(审核通过)
    MATCH_START_SOON = 3, //比赛快开始
    MATCH_START = 4, //球队赛/约球比赛开始
    
    NEW_MESSAGE = 5,// 消息列表新消息
    MATCH_PERSON_CHANGE = 6,// 约球球员增删改
    TEAM_MATCH_PERSON_CHANGE = 7,// 球队赛球员增删改
    TEAM_MATCH_STATUS_CHANGE = 8,// 比赛按钮状态改变
    NEW_TEAM_MATCH_APPLY = 9,// 比赛申请列表更新
    NEW_TEAM_APPLY = 10,// 球队申请列表更新
    TEAM_PERSON_CHANGE = 11,// 球队队员增删改
    NEW_FRIEND_APPLY = 12,// 新增好友申请
    FRIEND_LIST_CHANGE = 13,// 好友列表增删改
    MATCH_AUTO_END = 14,// 比赛自动结束
//    aaaaaa = 15,// <# 备注 #> 
//    aaaaaa = 16,// <# 备注 #>
    
} GWPushType;




@interface GWPushModel : NSObject


// 1 2 3 4 14 需要本地提示
@property(nonatomic,assign) GWPushType type;

@property (nonatomic, assign) NSInteger matchId;

@property (nonatomic, assign) NSInteger matchMode;//(100快速计分,200广场赛事)



@end

NS_ASSUME_NONNULL_END

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,185评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,445评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,684评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,564评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,681评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,874评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,025评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,761评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,217评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,545评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,694评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,351评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,988评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,778评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,007评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,427评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,580评论 2 349

推荐阅读更多精彩内容