Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background URLSession + Combine?

Tags:

swift

combine

When attempting to send a background request with URLSession's dataTaskPublisher method:

URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "example")) 
     .dataTaskPublisher(for: URL(string: "https://google.com")!) 
     .map(\.data) 
     .sink(receiveCompletion: { print($0) }) { print($0) }

I receive the error

Completion handler blocks are not supported in background sessions. Use a delegate instead.

This makes sense to me, sink is a bunch of completion handlers. So, I tried to build a Subscriber:

class ExampleSubscriber: Subscriber {
    typealias Input = Data

    typealias Failure = URLError

    func receive(subscription: Subscription) {
        subscription.request(.max(1))
    }

    func receive(_ input: Data) -> Subscribers.Demand {
        print(input)

        return Subscribers.Demand.none
    }

    func receive(completion: Subscribers.Completion<URLError>) {}

}

and subscribe with the Subscriber:

URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "example"))
    .dataTaskPublisher(for: URL(string: "https://google.com")!)
    .map(\.data)
    .subscribe(ExampleSubscriber())

and I receive the same error:

Completion handler blocks are not supported in background sessions. Use a delegate instead.

Is it possible to perform a background request using dataTaskPublisher or do I have to use a delegate to URLSession?

like image 383
Emma K Alexandra Avatar asked Mar 10 '26 09:03

Emma K Alexandra


1 Answers

URLSession.DataTaskPublisher is built on top of URLSessionDataTask and sets a completion handler on the task. So you cannot use DataTaskPublisher with a background session.

You can find the source code of DataTaskPublisher in the Swift project repo. Here are the relevant lines:

let task = p.session.dataTask(
    with: p.request,
    completionHandler: handleResponse(data:response:error:)
)
like image 92
rob mayoff Avatar answered Mar 13 '26 08:03

rob mayoff