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 ?
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With