I have the following extension on URLSession class :
extension URLSession {
@discardableResult
func sendRequest<A>(endpoint: Endpoint<A>, onComplete: @escaping (Result<A?, Error>) -> ()) -> URLSessionDataTask {
let task = dataTask(with: endpoint.request, completionHandler: { data, response, err in
if let err = err {
onComplete(.failure(err))
return
}
if let da = data, let a = try? JSONDecoder().decode(APIError.self, from: da) {
if a.error.message == "The username or password is wrong" {
onComplete(.failure(LoginErrors.uOrPincorrect))
}
if a.error.message == "Your account is locked" {
onComplete(.failure(LoginErrors.accountLocked))
}
return
}
task.resume()
return task
}
}
And then these structs and enums for Errors :
struct APIError: Decodable {
let error: APIErrorMessage
}
struct APIErrorMessage: Decodable {
let message: String
}
enum LoginErrors: String, Error {
case uOrPincorrect = "The username or password you entered is/are wrong"
case accountLocked = "Account Locked"
case unknownError = "Unknown error"
}
And lastly my call to a login web service :
func sessionCall(_ res: Result<LoginResponseData?, Error>) {
switch res {
case .success(let response):
...... // Some code
case .failure(let error):
self.showLoginError(error: //HOW TO GET THE STRING FROM ERROR HERE)
}
}
Thing is I want to get the string representing my enum in order to show the proper error message, but I can access this value at all. If I try with localizedDescription of the error I get a totally different string which has this content: "The operation could not be completed".