第一步:明确实现跳转的两个位置和APP的三种状态
(1)两个位置:
- didFinishLaunchingWithOptions代表的是收到通知的时候APP的状态可能是未启动
- didReceiveRemoteNotification代表的是收到通知的时候APP的状态可能是前台活跃(任何界面)、后台
(2)三种状态:未启动、前台活跃(任何界面)、后台,其中在前台活跃的时候接收到通知时,会在界面中间弹出提示框,一般不符合产品要求
第二步:具体的实现方式
(1)未启动:
//注册及属性赋值
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//1.注册
[UMessage startWithAppkey:kUMessageCode launchOptions:launchOptions];
[UMessage registerForRemoteNotifications];
[UMessage setLogEnabled:YES];
//2.获取推送的数据
NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
//3.添加属性且赋值
if(userInfo){
self.userInfo = userInfo;
}
return YES;
}
//在首页进行判断及加载:
- (void)viewDidLoad {
//未启动时-》接收推送消息
AppDelegate * app = (AppDelegate *)[UIApplication sharedApplication].delegate;
if (app.userInfo) {
//1.userInfo就是推送传来的数据
NSDictionary *pushMsgDic = app.userInfo;
//2.以pushMsgType字段作判断,跳转不同的界面
NSInteger pushMsgType = [[pushMsgDic objectForKey:@"pushMsgType"] integerValue];
.......
}
}
(2) 前台+后台
//app在前台或是后台-发送通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
//1.接受服务端推送通知传来的值,全部在userinfo里面。
[UMessage setAutoAlert:NO];
[UMessage didReceiveRemoteNotification:userInfo];
//2.发通知
//前台
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
[EBForeNotification handleRemoteNotification:userInfo soundID:1312 isIos10:NO];
//后台
}else{
[[NSNotificationCenter defaultCenter]postNotificationName:kPushMsgIINotification object:userInfo];
}
}
//在BaseViewController-接收和移除通知
-(void)viewWillAppear:(BOOL)animated{//接收通知
[super viewWillAppear:animated];
//后台推送-》接收通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushMsgJumpViewController:) name:kPushMsgIINotification object:nil];
//前台推送-》接收通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dddd:) name:EBBannerViewDidClick object:nil];
}
- (void)viewWillDisappear:(BOOL)animated{//移除通知
[super viewWillDisappear:animated];
//移除通知
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
第三步:功能优化
(1)app在前台时,推送过来的消息以通知栏的形式显示,而非提示框
附下载地址:https://github.com/Yasashi/EBForeNotification
(2)userId作为别名添加上,用来实现个推:
a:登录时添加别名,退出时删除别名
b:添加和删除别名时,“type”是可以自定义的,若是报错或者能添加别名确不能删除,则可能是添加和删除的不一致