2

I have a public function for local notification and i want to call that function in applicationWillTerminate. When i try this, nothing happens. I'm sure local notification function is ok because when i call that in viewDidLoad, it works properly.


This is the function for local notification;

func scheduleLocalNotification(second: Double) {

    if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.current()

        let content = UNMutableNotificationContent()
        content.badge = 1
        content.title = "Title!"
        content.body = "Message!"
        content.categoryIdentifier = "id"
        content.userInfo = ["key": "value"]
        content.sound = UNNotificationSound.default()

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: second, repeats: false)

        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
        center.add(request)
    } else {
        // Fallback on earlier versions
    }
}

AppDelegate;

func applicationWillTerminate(_ application: UIApplication) {

        scheduleLocalNotification(second: 30.0)
        print("Terminating!")

        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

I searched SO for similar problems and found 2 questions, but none of them solve my issue.

Send local notification after termination app swift 2

Local notification on application termination


Edit: Request Authorization;

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
        if (!launchedBefore)  {
            if #available(iOS 10.0, *) {
                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
                    if granted {
                        print("Authorization granted!")
                    } else {
                        print("Authorization not granted!")
                    }
                }
            } else {
                let settings = UIUserNotificationSettings(types: [.alert, .badge , .sound], categories: nil)
                UIApplication.shared.registerUserNotificationSettings(settings)
            }

            UserDefaults.standard.set(true, forKey: "launchedBefore")
        }

        // Override point for customization after application launch.
        return true
    }
Community
  • 1
  • 1
THO
  • 105
  • 1
  • 14
  • How are you terminating the app to test this? – Paulw11 Feb 14 '17 at 20:00
  • @Paulw11 hit the button twice and get rid of the app. I'm using real device for testing as well. – THO Feb 14 '17 at 20:05
  • Did you `requestAuthorization(options:completionHandler:)` somewhere earlier in your code? – rmp Feb 14 '17 at 20:09
  • 1
    [This solution](https://stackoverflow.com/a/41215347/1987) is a hack but it works for me. The gist of it is that the app got terminated before the notification can be scheduled. What the author of the hack did was to make the thread sleep. – Ronnie Liew Jul 11 '17 at 17:00

2 Answers2

0

An answer to the second question you linked to seems relevant - applicationWillTerminate is not guaranteed to get called if the system decides to terminate your app while it's in the background.

Uncommon
  • 3,323
  • 2
  • 18
  • 36
0

just a note about applicationWillTerminate: as Apple states, and "Uncommon" says, there is no guarantee that is called.

But I think is a design problem:

a) if You want to add a local notification, do it as soon as user have set it.

b) if You are passing via "applicationWillTerminate" to save cpu time calling "add notification" only when exiting, be sure there is no big penalty saving notifications every time. As a std behaviour, in iOS we should save everything as soon as user are set it.

in my apps I simply add notification on "back" or "close".

c) Be sure to control/reset notifications already set.

If you are only testing iOS behaviour, you are in corner edge, see "eskimo" answer here:

https://forums.developer.apple.com/thread/13557

ingconti
  • 10,876
  • 3
  • 61
  • 48