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
?