enum NetworkError: Error, LocalizedError {
case badURL
case dataError
case httpResponseError(Int)
case jsonError
var errorDescription: String {
switch self {
case .badURL:
return "Please check your URL"
case .dataError:
return "error in response data"
case .httpResponseError(let errorCode):
return "Error in response with responseCode \(errorCode)"
case .jsonError:
return "Unable to parse Json, Please check the Foemat"
}
}
}
class APIRequest: ObservableObject {
// Need to under stand how We are consuming Combine here
@Published var wordData: [WordDetails] = []
func getWordData(forWord text:String, completionHandler: @escaping (Result<[WordDetails], NetworkError>) -> Void) {
guard let url = URL(string: "https://api.dictionaryapi.dev/api/v2/entries/en/\(text)") else {
completionHandler(.failure(.badURL))
return
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard error == nil else {
completionHandler(.failure(.dataError))
return
}
if let response = response as? HTTPURLResponse,
!(200...299).contains(response.statusCode) {
completionHandler(.failure(.httpResponseError(response.statusCode)))
}
guard let data = data else {
completionHandler(.failure(.dataError))
return
}
do {
let decodedData = try JSONDecoder().decode([WordDetails].self, from: data)
DispatchQueue.main.async {
self.wordData = decodedData
}
completionHandler(.success(decodedData))
} catch {
completionHandler(.failure(.jsonError))
}
}
task.resume()
}
}