Search code examples
iosobjective-ciphoneios10uilocalnotification

How do I open the app when local notification is tapped with the new notification mechanisms?


application:didReceiveLocalNotification: is deprecated starting iOS10, and the developer page doesn't point to any alternatives.

UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"localnotification"
                                                                      content:content
                                                                      trigger:trigger];


UNUserNotificationCenter* notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
[notificationCenter requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                                  completionHandler:^(BOOL granted, NSError * _Nullable error) {
                          if (!error) {
                              NSLog(@"request authorization succeeded!");
                          }
                      }];


[notificationCenter addNotificationRequest:request
                     withCompletionHandler:nil];

I have created a notification as seen above with the appropriate content and trigger. Now I want the application to open when I tap said notification, but I can't seem to figure out how.


Solution

  • userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:

    This method from UNUserNotificationCenterDelegate needs to be implemented if you want to perform a custom action.

    - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
        if ([response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier]) {
            NSLog(@"app opened");
        }
    }