URLSession.shared.dataTaskPublisher not working on IOS 13.3

后端 未结 3 403
北恋
北恋 2020-12-03 23:36

When trying to make a network request, I\'m getting an error

finished with error [-999] Error Domain=NSURLErrorDomain Code=-999 \"cancelled\"
3条回答
  •  时光说笑
    2020-12-04 00:41

    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 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 = []
    
    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)
    }
    

提交回复
热议问题