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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With