杀死app点击通知栏跳转到指定页面(以本地通知为例)
第一步:两个控制器
1.ViewController
2.HelloViewController
我们杀死App或者在后台的时候点击通知栏跳转到HelloViewController里
AppDelegate.m
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
self.window.rootViewController = [ViewController new];
// 如果 launchOptions 不为空
if (launchOptions) {
// 获取推送通知定义的userinfo
UILocalNotification *notification = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
NSString *controller = notification.userInfo[@"controller"];
// 这里就是告诉程序我要跳转到哪里
if ([controller isEqualToString:NSStringFromClass([HelloViewController class])]) {
HelloViewController *hello = [HelloViewController new];
hello.userInfo = launchOptions;
[self.window.rootViewController presentViewController:hello animated:YES completion:nil];
}
}
第二步:然后在ViewController.m里加入通知(具体在哪这个随你的项目去设置)
ViewController.m
// 注册通知 iOS8以后用这个 (现在已经有iOS10的新的推送方法了)
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
// 删除所有的通知 这句话需不需要看你的需求了。
[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *noti = [[UILocalNotification alloc] init];
noti.repeatInterval = NSCalendarUnitMinute; // 每分钟推送一次
noti.fireDate = [NSDate date]; // 当前时间
noti.alertBody = @"推送消息";
noti.alertTitle = @"Test";
noti.soundName = UILocalNotificationDefaultSoundName;
noti.userInfo = @{@"controller": @"HelloViewController"};
[[UIApplication sharedApplication] scheduleLocalNotification:noti]; // 加入推送
最后一步:在HelloViewController里我们做一些事情把页面改成红色告诉我们已经成功跳转到这里了。
HelloViewController.m
self.view.backgroundColor = [UIColor redColor];
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 200, [UIScreen mainScreen].bounds.size.width, 200)];
UILocalNotification *notification = self.userInfo[UIApplicationLaunchOptionsLocalNotificationKey];
textView.text = [NSString stringWithFormat:@"%@", notification.userInfo[@"controller"]];
[self.view addSubview:textView];
OK 运行 回到杀死App 点击推送消息 跳转完成
<第一次写简书,是一些比较简单的东西,工作中遇到了就记录下来了,请尽力吐槽。>