Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

If I use URLSession.shared.dataTask instead of URLSession.shared.dataTaskPublisher it will work on IOS 13.3.

Here is my code :

return  URLSession.shared.dataTaskPublisher(for : request).map{ a in
    return a.data
}
.decode(type: MyResponse.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()

This code worked on IOS 13.2.3.

like image 426
Rasul Avatar asked Dec 11 '19 06:12

Rasul


1 Answers

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)
}
like image 141
Procrastin8 Avatar answered Jan 04 '23 09:01

Procrastin8