Skip to content

Instantly share code, notes, and snippets.

@wata
Created April 7, 2020 14:06
Show Gist options
  • Save wata/59b8f7e7205840b6b2b6a0c08fbdf8c0 to your computer and use it in GitHub Desktop.
Save wata/59b8f7e7205840b6b2b6a0c08fbdf8c0 to your computer and use it in GitHub Desktop.
Avoid app termination without calling the `endBackgroundTask(_:)`.
import UIKit
final class BackgroundTask {
private var taskID = UIBackgroundTaskIdentifier.invalid
func begin(withName taskName: String = #function) {
taskID = UIApplication.shared.beginBackgroundTask(withName: taskName) {
UIApplication.shared.endBackgroundTask(self.taskID)
self.taskID = UIBackgroundTaskIdentifier.invalid
}
}
func end() {
guard taskID != UIBackgroundTaskIdentifier.invalid else { return }
UIApplication.shared.endBackgroundTask(taskID)
}
deinit {
end()
}
}
@wata
Copy link
Author

wata commented Apr 7, 2020

Usage

func sendDataToServer(data: NSData) {
    // Perform the task on a background queue.
    DispatchQueue.global().async {
        let task = BackgroundTask()
        task.begin()

        // Send the data synchronously.
        self.sendAppDataToServer( data: data)

        // End the task assertion.
        task.end()
    }
}

// Prints if timeout "[BackgroundTask] Background Task 16 ("sendDataToServer(data:)"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this."

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