后台 URLSession + Combine?
Background URLSession + Combine?
尝试使用 URLSession
的 dataTaskPublisher
方法发送后台请求时:
URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "example"))
.dataTaskPublisher(for: URL(string: "https://google.com")!)
.map(\.data)
.sink(receiveCompletion: { print([=10=]) }) { print([=10=]) }
我收到错误
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. Here are the relevant lines的源代码:
let task = p.session.dataTask(
with: p.request,
completionHandler: handleResponse(data:response:error:)
)
尝试使用 URLSession
的 dataTaskPublisher
方法发送后台请求时:
URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "example"))
.dataTaskPublisher(for: URL(string: "https://google.com")!)
.map(\.data)
.sink(receiveCompletion: { print([=10=]) }) { print([=10=]) }
我收到错误
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. Here are the relevant lines的源代码:
let task = p.session.dataTask( with: p.request, completionHandler: handleResponse(data:response:error:) )