Search code examples
iosswiftpush-notificationapple-push-notificationsonesignal

OSRemoteNotificationReceivedHandler equivalent for iOS


I can opt into receiving a push notification in Android, but on IOS I can't find an equivalent way to do the same.

In android I can override:

@Override
public void remoteNotificationReceived(Context context, OSNotificationReceivedEvent notificationReceivedEvent) {
    OSNotification notification = notificationReceivedEvent.getNotification();
    notificationReceivedEvent.complete(notification);
    <-- I can do something with the notification data here.
}

How can I do the same in iOS?

I'm using onesignal, if that makes any difference.


Solution

  • On iOS the user has to opt in to receive notifications. I would suggest following a tutorial for the whole process. Here is a tutorial from Ray Wenderlich.

    Assuming you have done all of the setup, the code you are looking for is inside the UNUserNotificationCenterDelegate. Specifically,

    @available(iOS 10.0, *)
    optional func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
    
    @available(iOS 10.0, *)
    optional func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async
    

    depending on if you want async or closures.