Hey guys, I am currently learning about Combine framework and how to use it. I am quite amazed but there are some things that still make me feel dull.
For example. I've got that network call that I am working on.
private func fetchFollowersAppleWay() {
guard let url = URL(string: endPointString) else { return }
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
var fetchFollowersCancellable = URLSession.shared
.dataTaskPublisher(for: url)
.tryMap { element -> Data in
guard let httpResponse = element.response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
throw URLError(.badServerResponse)
}
return element.data
}
.decode(type: [Follower].self, decoder: decoder)
.sink { error in
self.fetchingError = error
// Cannot assign value of type 'Subscribers.Completion<Error>' to type 'Error?'
} receiveValue: { followers in
self.followers = followers
}
}
My main point right now, is to handle errors as well as possible. With UIKit, I would have handled it like this:
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let _ = error { completed(.failure(.unableToComplete))}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else { completed(.failure(.invalidResponse)); return}
guard let data = data else { completed(.failure(.invalidData)); return}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let followers = try decoder.decode([Follower].self, from: data)
completed(.success(followers))
} catch { completed(.failure(.invalidData)) }
I am not sure how to handle errors properly with that newer Publisher. Any help appreciated, thanks!