Reputation: 53
When app is closed and it gets a push notification, I want to quickly process the notification and show it to user, then let app go back to closed (or maybe suspended). Instead, the app stays running and even tries to load the root view controller. My code registers for background work, and unregisters when done.
var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
func registerBackgroundTask() {
if backgroundTask == UIBackgroundTaskInvalid {
backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
self?.endBackgroundTask()
}
assert(backgroundTask != UIBackgroundTaskInvalid)
}
}
func endBackgroundTask() {
print("Background task ended.")
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
I'm able to test my code using Xcode to attach to my app when it launches due to new APNs push notification. After the notification processing completes, app is still alive. Do I need to force app to suspend? I thought iOS would just close or suspend the app when it finishes processing the notification and I call endBackgroundTask. Also, if I close Xcode so app debugger stops, then launch it on my device I see it is running and showing the root view controller (although not fully initialized since that code isn't run for this type of launch). What am I missing?
Upvotes: 0
Views: 179
Reputation: 929
First, calling 'registerBackgroundTask' twice will cause 'backgroundTask' to be overwritten and you are going to lose the ability to end task other than the latest one.
Instead, the app stays running and even tries to load the root view controller.
Second, make sure you read about application lifecycle: [1] and delegate methods [2]. Typically your app will be in the background (be it in background execution mode or in suspended state) but it is also possible for push notification to force your app to be launched (in case it is not running at all). It is then up to you to handle it gracefully and to not load the UI in case it is not necessary.
1 - https://developer.apple.com/documentation/uikit/core_app/managing_your_app_s_life_cycle 2 - https://developer.apple.com/documentation/uikit/uiapplicationdelegate
Upvotes: 0