URLSession.shared.dataTaskPublisher在IOS 13.3上不起作用 [英] URLSession.shared.dataTaskPublisher not working on IOS 13.3
问题描述
尝试发出网络请求时,出现错误
When trying to make a network request, I'm getting an error
finished with error [-999] Error Domain=NSURLErrorDomain Code=-999 "cancelled"
如果我使用 URLSession.shared.dataTask
而不是 URLSession.shared.dataTaskPublisher
,它将在IOS 13.3上运行.
If I use URLSession.shared.dataTask
instead of URLSession.shared.dataTaskPublisher
it will work on IOS 13.3.
这是我的代码:
return URLSession.shared.dataTaskPublisher(for : request).map{ a in
return a.data
}
.decode(type: MyResponse.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
此代码适用于IOS 13.2.3.
This code worked on IOS 13.2.3.
推荐答案
您没有显示足够的代码,但是根据症状,您可以清楚地知道问题所在:发布者/订阅者对象的生存时间不够长.我敢说您的代码总是错误的,这似乎是成功的怪癖.确保您的发布者(尤其是您的订阅者)保留在长期存在的对象(例如实例属性)中,以便有时间进行网络通信.
You have not shown enough code, but based on the symptom it is clear what the problem is: your publisher / subscriber objects are not living long enough. I would venture to say that your code was always wrong and it was just a quirk that it seemed to succeed. Make sure that your publisher and especially your subscriber are retained in long-lived objects, such as instance properties, so that the network communication has time to take place.
这是一个如何使用数据任务发布者的可行示例:
Here's a working example of how to use a data task publisher:
class ViewController: UIViewController {
let url = URL(string:"https://apeth.com/pep/manny.jpg")!
lazy var pub = URLSession.shared.dataTaskPublisher(for: url)
.compactMap {UIImage(data: $0.data)}
.receive(on: DispatchQueue.main)
var sub : AnyCancellable?
override func viewDidLoad() {
super.viewDidLoad()
let sub = pub.sink(receiveCompletion: {_ in}, receiveValue: {print($0)})
self.sub = sub
}
}
这会打印< UIImage:0x6000008ba490匿名{180,206}>
,这是正确的(如您自己转到该URL所见).
That prints <UIImage:0x6000008ba490 anonymous {180, 206}>
, which is correct (as you can see by going to that URL yourself).
我要说的是,如果您不说 self.sub = sub
,您将得到报告的错误:订阅者 sub
,仅仅是本地的,它会立即不复存在,并且网络交易会被过早取消(由于您报告了错误).
The point I'm making is that if you don't say self.sub = sub
, you get exactly the error you are reporting: the subscriber sub
, which is merely a local, goes out of existence immediately and the network transaction is prematurely cancelled (with the error you reported).
编辑我认为代码是在 .store(in:)
方法存在之前编写的;如果我今天写的话,我会用它代替 sub
属性.但是原理是一样的.
EDIT I think that code was written before the .store(in:)
method existed; if I were writing it today, I'd use that instead of a sub
property. But the principle is the same.
这篇关于URLSession.shared.dataTaskPublisher在IOS 13.3上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!