1

I'm trying to delete all pending notifications when user quit the app

So I added this code
func applicationWillTerminate(_ application: UIApplication) { print("This function was executed") application.unregisterForRemoteNotifications() } at AppDelegate.swift to delete all pending notifications when user quit the app.

But it didn't work. So I added print("This function was executed") and actually quit the app to see whether Xcode prints "This function was executed"

But Xcode doesn't print This "function was executed"

How can I fix this?

Seungjun
  • 874
  • 9
  • 21
  • Can you be more precise about what you mean by "quit the app". – Rudedog Feb 28 '20 at 17:08
  • @Rudedog I meant terminating the app, (not entering background) – Seungjun Feb 28 '20 at 17:11
  • 2
    Terminating an app by swiping it away or hitting stop in Xcode ends the app immediately; iOS does not make any callbacks.`applicationWillTerminate(_:)` is typically only called if iOS decides to evict a background app from memory. – Rudedog Feb 28 '20 at 17:16
  • Thank u for the response, then what function should when I want it to be executed app got terminated by swiping it away? – Seungjun Feb 28 '20 at 17:20
  • 1
    You can't. You should re-design your app to do this in some other way. – Rudedog Feb 28 '20 at 17:24
  • 1
    Here's some more discussion that might help you: [link](https://stackoverflow.com/questions/32223037/how-to-execute-code-when-my-app-terminated-in-background-in-ios) – developingbassist Feb 28 '20 at 17:28

1 Answers1

1

This code example to remove all pending notification.

func applicationWillTerminate(_ application: UIApplication) {
   UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}

This code example for unregistering remote notifications.

func applicationWillTerminate(_ application: UIApplication) {
    UIApplication.shared.unregisterForRemoteNotifications()
}
AMIT
  • 906
  • 1
  • 8
  • 20
  • thanks u for the response, I added that function at 'AppDelegate.swift' , but sadly that function doesn't get executed. I tried checking with adding a line of printing some string, but Xcode doesn't print that string at all – Seungjun Feb 28 '20 at 17:47
  • My Xcode Version 11.3.1 (11C504). And I am able to print inside the application will terminate function after the app quite. – AMIT Feb 28 '20 at 17:56