Remote notification when app is terminated

1.1k views Asked by At

I am new to iOS and Swift. I am implementing remote notification in my app. Everything works fine when the app is active or in the background. But my notification does not show up when the app is terminated. All I am getting is the alert sound of the notification.

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if #available(iOS 10.0, *){
    }else{
        let notification = UILocalNotification()
        notification.alertTitle = "my Title"
        notification.alertBody = "My Message"
        notification.category = "customCategory"
        notification.soundName = UILocalNotificationDefaultSoundName
        application.scheduleLocalNotification(notification)
    }
}
1

There are 1 answers

1
user3608500 On

Below AppDelegate method will be called When you receive a notification and application is in killed state

didFinishLaunchingWithOptions

So you should handle it properly from here when app is in killed state.

Below code helps to identify the Remote/push or Local notification in didFinishLaunchingWithOptions method:

if let launchOpts = launchOptions as [UIApplicationLaunchOptionsKey: Any]? {
            if let notificationPayload = launchOpts[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {

                 //Handle push notification here
                }
else if let notification = (launchOpts as NSDictionary).object(forKey: "UIApplicationLaunchOptionsLocalNotificationKey") as? UILocalNotification {
               //Handle local notification here
                }