ios-利用本地通知跳转到应用程序指定界面

来源:互联网 发布:中信证券网上交易软件 编辑:程序博客网 时间:2024/05/16 09:48

我们如果想要点击按钮跳转到相应的界面的话我们可以这么做,举个例子,就拿UITabBarController来说事,控制器如下所示


比如说我们在前台的时候,我们可以通过发送通知就能实现应用程序的跳转,我们可以发送以下的通知,然后去拼接UNMutableNotificationContent的userInfo内容,我们可以把下面的代码添加到一个UIButton的点击方法中。

 UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];  content.title = @"sss";  content.body = @"哈哈";  content.badge = @5;  content.sound = [UNNotificationSound defaultSound];  //重点是里面的selectIndex的值   content.userInfo = @{@"selectIndex":@(1)};  UNTimeIntervalNotificationTrigger * trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];  //包装成通知请求   UNNotificationRequest * request = [UNNotificationRequest requestWithIdentifier:@"tongzhi" content:content trigger:trigger];        //通知中心添加这个通知请求    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {            }];
然后我们可以去实现下面这个代理方法,在里面进行处理,这样在前台的时候就可以做到点击按钮可以调到指定的页面

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{         //当然这里需要去判断userInfo的值,我这里就先不去判断了,准确的话一定要进行判断的,毕竟通知有很多个    //在这里也可以做页面跳转    UITabBarController * vc = (UITabBarController *)self.window.rootViewController;       vc.selectedIndex = [notification.request.content.userInfo[@"selectIndex"]intValue];        //这里设置没有提示    completionHandler(UNNotificationPresentationOptionNone);}
我们如果想要后台做点击通知就能跳转到指定的界面的话就要去实现下面那个代理方法

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{   //这里也是需要去判断userInfo的值的,我这里也省略了   UITabBarController * vc = (UITabBarController *)self.window.rootViewController;    vc.selectedIndex = [response.notification.request.content.userInfo[@"selectIndex"]intValue];        completionHandler();}
这两个代理方法都是在UNUserNotificationCenterDelegate,这个协议里面的,我们一般是设置UNUserNotificationCenter的代理,代理需要遵守UNUserNotificationCenterDelegate这个协议,然后我们再去实现上面两个代理方法。