Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update completion handler with result type and error handling in better approach #1

Open
RaviRanjan-11 opened this issue Sep 1, 2022 · 0 comments

Comments

@RaviRanjan-11
Copy link

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()
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant