gpt4 book ai didi

swift - 后台 URLSession + Combine?

转载 作者:行者123 更新时间:2023-12-04 15:26:40 26 4
gpt4 key购买 nike

当尝试使用 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 的委托(delegate)?

最佳答案

URLSession.DataTaskPublisher 建立在 URLSessionDataTask 之上,并在任务上设置完成处理程序。所以你不能在后台 session 中使用 DataTaskPublisher

您可以找到DataTaskPublisher 的源代码in the Swift project repo .这里是the relevant lines :

let task = p.session.dataTask(
with: p.request,
completionHandler: handleResponse(data:response:error:)
)

关于swift - 后台 URLSession + Combine?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62108591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com