Skip to content

Instantly share code, notes, and snippets.

@damodarnamala
Forked from stinger/CombineFetcher.swift
Created September 16, 2022 03:47
Show Gist options
  • Save damodarnamala/165c1f8c7a5deac0e288504f7660734e to your computer and use it in GitHub Desktop.
Save damodarnamala/165c1f8c7a5deac0e288504f7660734e to your computer and use it in GitHub Desktop.
Combine - fetching data using URLSession publishers
import Foundation
import Combine
enum APIError: Error, LocalizedError {
case unknown, apiError(reason: String)
var errorDescription: String? {
switch self {
case .unknown:
return "Unknown error"
case .apiError(let reason):
return reason
}
}
}
func fetch(url: URL) -> AnyPublisher<Data, APIError> {
let request = URLRequest(url: url)
return URLSession.DataTaskPublisher(request: request, session: .shared)
.tryMap { data, response in
guard let httpResponse = response as? HTTPURLResponse, 200..<300 ~= httpResponse.statusCode else {
throw APIError.unknown
}
return data
}
.mapError { error in
if let error = error as? APIError {
return error
} else {
return APIError.apiError(reason: error.localizedDescription)
}
}
.eraseToAnyPublisher()
}
// Usage
guard let url = URL(string: "https://www.amazon.com") else { return }
fetch(url: url)
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
break
case .failure(let error):
print(error.localizedDescription)
}
}, receiveValue: { data in
guard let response = String(data: data, encoding: .utf8) else { return }
print(response)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment