In RestManager class, using URLSession I want to return AnyPublisher<Result<T, ErrorType>, Never>.
So I made this code
class RestManager {
func fetchData<T: Decodable>(url: URL) -> AnyPublisher<Result<T, ErrorType>, Never> {
return Future<Result<T, ErrorType>, Never> { promise in
URLSession
.shared
.dataTask(with: url) { data, response, error in
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
if let data = try? JSONDecoder().decode(T.self, from: data!){
promise(.success(.success(data)))
}else {
promise(.success(.failure(.empty)))
}
}
else if let error = error as? URLError {
switch error.code {
case .notConnectedToInternet, .networkConnectionLost, .timedOut:
promise(.success(.failure(.noInternetConnection)))
case .cannotDecodeRawData, .cannotDecodeContentData:
promise(.success(.failure(.empty)))
default:
break
}
}else {
promise(.success(.failure(.general)))
}
}
}
.eraseToAnyPublisher()
}
}
But when I call this function in viewModel it returns empty array, but there is not any error thrown. I used breakpoints on if and else statements and program is actually not executing them.
CodePudding user response:
A standard dataTask
of URLSession
must be resumed
URLSession
.shared
.dataTask(with: url) { data, response, error in
...
}
.resume()
An alternative is Combine's .dataTaskPublisher(for