[尝试使用URLSession
的dataTaskPublisher
方法发送后台请求时:
URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "example"))
.dataTaskPublisher(for: URL(string: "https://google.com")!)
.map(\.data)
.sink(receiveCompletion: { print($0) }) { print($0) }
我收到错误
Completion handler blocks are not supported in background sessions. Use a delegate instead.
这对我来说很有意义,sink
是一堆完成处理程序。因此,我尝试构建一个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>) {}
}
并订阅Subscriber
:
URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "example"))
.dataTaskPublisher(for: URL(string: "https://google.com")!)
.map(\.data)
.subscribe(ExampleSubscriber())
并且我收到相同的错误:
Completion handler blocks are not supported in background sessions. Use a delegate instead.
是否可以使用dataTaskPublisher
执行后台请求,或者我必须使用URLSession
的委托?
URLSession.DataTaskPublisher
建立在URLSessionDataTask
之上,并为任务设置完成处理程序。因此,您不能在后台会话中使用DataTaskPublisher
。
您可以找到DataTaskPublisher
in the Swift project repo的源代码。这是the relevant lines:
let task = p.session.dataTask( with: p.request, completionHandler: handleResponse(data:response:error:) )