App is in foreground
Implement didReceiveRemoteNotification delegate method in AppDelegate to handle the notification and run the code you want when app is in foreground.
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
//write your code here when app is in foreground
}
App is in background
When the app is in background and user receives push notification, didReceiveRemoteNotification will get called if user taps on the notification but if the user taps on App icon then this method will not get called, In this case you have to communicate with your server or you can check the badge number with the previous value(you can store it in NSUserDefaults) and run the code you want.
App has been terminated
When the app has been terminated didReceiveRemoteNotification method will not get called,
But you can check launchOptions to know weather the application has been launched from notification or not in didFinishWithLaunchOptions method in appdelegate and do your task accordingly.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
if launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] != nil {
// Do your task here
}
}