URLSession.shared.dataTaskPublisher 不适用于 IOS 13.3 [英] URLSession.shared.dataTaskPublisher not working on IOS 13.3

查看:24
本文介绍了URLSession.shared.dataTaskPublisher 不适用于 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.

推荐答案

您在这里有 2 个问题:1. 就像@matt 所说的,你的出版商活得不够久.您可以将 AnyCancellable 存储为实例 var,或者我喜欢做的(似乎是 redux 最佳实践)是使用 store(in:)Set 以保留它并在对象被释放时自动清理它.2. 为了启动实际的网络请求,您需要sinkassign 值.

You have 2 problems here: 1. like @matt said, your publisher isn't living long enough. You can either store the AnyCancellable as an instance var, or what I like to do (and appears to be a redux best practice) is use store(in:) to a Set<AnyCancellable> to keep it around and have it automatically cleaned up when the object is dealloced. 2. In order to kick off the actual network request you need to sink or assign the value.

所以,把这些放在一起:

So, putting these together:

var cancellableSet: Set<AnyCancellable> = []

func getMyResponse() {
  URLSession.shared.dataTaskPublisher(for : request).map{ a in
    return a.data
  }
  .decode(type: MyResponse.self, decoder: JSONDecoder())
  .receive(on: DispatchQueue.main)
  .replaceError(with: MyResponse())
  .sink { myResponse in print(myResponse) }
  .store(in: &cancellableSet)
}

这篇关于URLSession.shared.dataTaskPublisher 不适用于 IOS 13.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆