iosswiftlocalnotification

Swift - Execute function when receive Local Notification in app in background


I am creating an app that the user schedules some tasks in a certain time interval and the application sends local notifications to alert the user.

I am using UNUserNotificationCenter to schedule the notifications and everything is working normally but I need every time the notification is received, execute a function that would save the notification data in a database.

If I use the userNotificationCenter (_: didReceive: withCompletionHandler :) function only when the user taps the notification.

If I use the userNotificationCenter (_: willPresent: withCompletionHandler :) function I can run only when the application is running.

With these two options above I can not save to the database when the notification arrives with the application in the background and the user does not click. Does anyone know of any other function that I can call this case? OR a way of executing a function when the notification is received.


Solution

  • You just can't :( UserNotification was made to show some information to user, not to schedule a task in application. Hope this will change in iOS 13 - as Apple says: "iOS 13 adds a new background tasks API to the platform which allows apps to schedule activities to run in the background without forcing users to open the app and let it run in the foreground."