I am not sure if this is not possible or if I am implementing it wrong.
I am trying to complete a task in the background using beginBackgroundTask
(expirationHandler
) and then post a LocalNotification
once it is complete on iOS10
. The issue is that the Notification
will not consistently fire - I can set a breakpoint
to see it scheduled using presentLocalNotificationNow
but it does not always display to the user and only once the app comes back to the foreground
(by opening it from the home screen) does didReceiveLocalNotification
get called.
If I check the application state when I am scheduling the notification it has a rawValue of 2 which I believe is inactive so I'm assuming that is the reason it is not delivering the notification to the user.
I've tried scheduling the notification
for 5 secs after the completion of the task and then calling endBackgroundTask
immediately but the notification still doesn't consistently show to the user. EndBackgroundTask
does get called which I would assume should move the application to the background from inactive at which point the notification
should show but I'm assuming it is not immediate and at the system's discretion when that actually happens.
What am I doing wrong?
The relevant code is:
let task = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
// Long running task
let notification = UILocalNotification()
notification.soundName = UILocalNotificationDefaultSoundName
notification.alertBody = "Message"
let settings = UIUserNotificationSettings(types: [.alert, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.presentLocalNotificationNow(notification)
UIApplication.shared.endBackgroundTask(task)
Best I can tell, the issue was due to presentLocalNotificationNow being async and returning immediately so there wasn't enough time for the system to register the notification. I solved the issue by scheduling the notification earlier so there was enough time.