Issue while displaying correctly an error message for Invalid credentials

75 views Asked by At

I would like to display the content of the error received from my server in my iPad apps using Swift, but I can not display it correctly:

(lldb) po (response.rawString)
"{\"message\":\"Invalid Credentials\"}"

I would like to display only : Invalid Credentials

1

There are 1 answers

0
Witek Bobrowski On

You could add a custom type for your error and make it conform to Codable

struct ServerError: Error, Codable {
    let message: String
}

and then decode value of response.rawString using JSONDecoder

let decoder = JSONDecoder()
guard
    let data = response.rawString.data(using: .utf8),
    let error = try? decoder.decode(ServerError.self, from: data)
else {
    return
}
print(error.message) // output: Invalid Credentials