【发布时间】:2021-03-10 07:10:22
【问题描述】:
我想使用 Swift 在我的 iPad 应用程序中显示从我的服务器收到的错误内容,但我无法正确显示:
(lldb) po (response.rawString)
"{\"message\":\"Invalid Credentials\"}"
我只想显示: 无效的凭据
【问题讨论】:
我想使用 Swift 在我的 iPad 应用程序中显示从我的服务器收到的错误内容,但我无法正确显示:
(lldb) po (response.rawString)
"{\"message\":\"Invalid Credentials\"}"
我只想显示: 无效的凭据
【问题讨论】:
您可以为您的错误添加自定义类型并使其符合Codable
struct ServerError: Error, Codable {
let message: String
}
然后使用JSONDecoder解码response.rawString的值
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
【讨论】: