Background URLSession + Combine?

问题描述 投票:1回答:1

[尝试使用URLSessiondataTaskPublisher方法发送后台请求时:

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的委托?

swift combine
1个回答
1
投票

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:)
)
© www.soinside.com 2019 - 2024. All rights reserved.