Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if user has taken action local notification or remote notification?

I am displaying local and remote notifications in my app. Now there is scenario if the notification is local then I want to take a different action or if the the notification is remote then I want to take some different action.

Till iOS 9 I was using below code to detect if the notification is local or remote.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {


    if launchOptions?[UIApplicationLaunchOptionsKey.localNotification] != nil {
        // Do what you want to happen when a remote notification is tapped.
    }
    return true
  }

But in iOS 10 this approach is deprecated so now how do I make sure the notification is local or remote ?

like image 219
TechChain Avatar asked Dec 02 '22 12:12

TechChain


2 Answers

For iOS 10 and above using UserNotifications framework.

To check user has taken an action on a notification. You can conform to UNUserNotificationCenterDelegate and implement userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:

To check if it is a remote notification. You can check type of trigger, since remote notifications trigger is UNPushNotificationTrigger.

Here's the code...

#pragma mark - UNUserNotificationCenterDelegate

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

    if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        // User did tap at remote notification
    }

    completionHandler();
}
like image 147
nRewik Avatar answered Apr 05 '23 23:04

nRewik


In UNMutableNotificationContent add userInfo in like below:

content.userInfo = ["isLocalNotification" : true]

Now in AppDelegate set UNUserNotificationCenterDelegate in didFinishLaunchingWithOptions like below:

UNUserNotificationCenter.current().delegate = self

Then implement didReceive response method of UNUserNotificationCenterDelegate:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        print(response.notification.request.content.userInfo)
    }

in output you will get something like below:

[AnyHashable("isLocalNotification"): 1]

you can identify Local Notification with isLocalNotification key.

like image 40
iVarun Avatar answered Apr 06 '23 00:04

iVarun