Skip to content

Instantly share code, notes, and snippets.

@quangtqag
Last active August 31, 2023 02:15
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quangtqag/d63f887c3a5426127840 to your computer and use it in GitHub Desktop.
Save quangtqag/d63f887c3a5426127840 to your computer and use it in GitHub Desktop.
Make app always call applicationWillTerminate
func applicationDidEnterBackground(application: UIApplication) {
// Create a pseudo background task to system call applicationWillTerminate when app enter background
// Default system will not call applicationWillTerminate when app enter background
// applicationWillTerminate only called when user close app in app switcher or some special cases of system
bgTask = application.beginBackgroundTaskWithExpirationHandler({ () -> Void in
application.endBackgroundTask(self.bgTask)
self.bgTask = UIBackgroundTaskInvalid
})
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
self.bgTask = UIBackgroundTaskInvalid
application.endBackgroundTask(self.bgTask)
}
}
@Hazoomo
Copy link

Hazoomo commented May 7, 2018

# Thanks A lot save my day .

This code for Swift 3


var bgTask : UIBackgroundTaskIdentifier!

func applicationDidEnterBackground(_ application: UIApplication) {
        // Create a pseudo background task to system call applicationWillTerminate when app enter background
        // Default system will not call applicationWillTerminate when app enter background
        // applicationWillTerminate only called when user close app in app switcher or some special cases of system
        bgTask = application.beginBackgroundTask(expirationHandler: { () -> Void in
            application.endBackgroundTask(self.bgTask)
            self.bgTask = UIBackgroundTaskInvalid
        })
        
        DispatchQueue.global(qos : .background).async() { () -> Void in
            self.bgTask = UIBackgroundTaskInvalid
            application.endBackgroundTask(self.bgTask)
        }
    }

@killann
Copy link

killann commented Jul 2, 2018

Hello, could you please explain why we should dispatch on other queue task completion?
@quangtqag

    DispatchQueue.global(qos : .background).async() { () -> Void in
          self.bgTask = UIBackgroundTaskInvalid
          application.endBackgroundTask(self.bgTask)
      }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment