await UIApplication.shared.beginBackgroundTask inside an async method

Looking for tips here. I've got Swift Concurrency Checking set to Complete - so I'm seeing interesting warnings that I'd like to hear what the proper way to fix this is.

I've got an async method that I'm using in a variety of places that I need to specify is a task that needs to complete even if the user goes into the background. It can take 2-60 seconds depending on DNS/network and server responses.

func checkRoutineDepartures() async {
        var bgTaskId: UIBackgroundTaskIdentifier = .invalid
        bgTaskId = await UIApplication.shared.beginBackgroundTask(withName: "checkRoutineDepartures") {
            UIApplication.shared.endBackgroundTask(bgTaskId)
            bgTaskId = .invalid
        }

With the complete option, I get a warning Non-sendable type '(() -> Void)?' passed in call to main actor-isolated function cannot cross actor boundary on the completion handler and then on the endBackgroundTask line I get Call to main actor-isolated instance method 'endBackgroundTask' in a synchronous nonisolated context; this is an error in Swift 6

In the docs for both of these, it says I can call them

This method can be safely called on a non-main thread.

So it seems to me like the headers are incorrectly marking the entire class as Main Actor and missing these methods, or I'm doing something wrong.

Post not yet marked as solved Up vote post of alex_kac Down vote post of alex_kac
789 views
Add a Comment

Replies

I truly believe you are right. Either the block parameter should be marked @Sendable on Apple's side, or the function should be nonisolated. This has probably been overlooked.

  • Is there any kind of workaround for this?

  • I marked my block: parameter @Sendable: await UIApplication.shared.beginBackgroundTask(withName: "someName") { @Sendable in ... } and the warning went away.

Add a Comment