Как получить конкретный вид контроллера по щелчку локального уведомления?.. Я пытался все возможные пути для достижения, но не смог

У меня есть два контроллера вида на первом контроллере, имеющем кнопку, при нажатии которой срабатывает локальное уведомление, но я хочу открыть второй контроллер вида при щелчке локального уведомления. Прошел все соответствующие посты, но не смог найти решение.

Мой код: В первом представлении вид контроллера сделал Load:

 isGrantedNotificationAccess = false;
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    UNAuthorizationOptions options =  UNAuthorizationOptionSound + UNAuthorizationOptionAlert;
    [center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError * _Nullable error) {
        isGrantedNotificationAccess = granted;
    }];

Действие кнопки только в контроллере первого вида:

 - (IBAction)buttonAction:(id)sender {
    if (isGrantedNotificationAccess) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        UNMutableNotificationContent *muContent = [[UNMutableNotificationContent alloc] init];
        muContent.title = @"Keshav Title";
        muContent.subtitle = @"He is an iOS Developer";
        muContent.body = @"He is a body";
        muContent.sound = [UNNotificationSound defaultSound];
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:3 repeats:NO];
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"UYLocalNotification" content:muContent               trigger: trigger];

        [center addNotificationRequest:request withCompletionHandler:nil];
    }
} 

В appdelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate  = self;
    return  YES;
}


-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    UNNotificationPresentationOptions present = UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound ;
    completionHandler(present);
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{

    if(application.applicationState == UIApplicationStateActive) {
        //app is currently active, can update badges count here
    } else if(application.applicationState == UIApplicationStateBackground){
        //app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here
        self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
        UIViewController *viewController =  [storyboard instantiateViewControllerWithIdentifier:@"secondViewController"];
        self.window.rootViewController = viewController;
        [self.window makeKeyAndVisible];
    } else if(application.applicationState == UIApplicationStateInactive){
        //app is transitioning from background to foreground (user taps notification), do what you need when user taps here
    }
}

1 ответ

Решение

В AppDelegate

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       didReceiveNotificationResponse:(UNNotificationResponse *)response
       withCompletionHandler:(void (^)(void))completionHandler {



      UINavigationController *nvc = (UINavigationController *)self.window.rootViewController;

      // Currently visible ViewController
      UIViewController *vc = nvc.visibleViewController;

      UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main"
                                             bundle:NULL];
      // YourViewController to Push in Your case SecondViewController
      yourViewController *myVc= [sb instantiateViewControllerWithIdentifier:@"yourViewController"];

      [navigationController pushViewController:myVc animated:true];
}

Вы можете проверить конкретное уведомление по response.actionIdentifier

в вашем случае с response.notification.request.content.categoryIdentifierВы проверяете конкретное уведомление

Установить catagoryIdentifier

muContent.categoryIdentifier = @"Your_Identifier";
Другие вопросы по тегам