【问题标题】:Issue while displaying correctly an error message for Invalid credentials正确显示无效凭据的错误消息时出现问题
【发布时间】:2021-03-10 07:10:22
【问题描述】:

我想使用 Swift 在我的 iPad 应用程序中显示从我的服务器收到的错误内容,但我无法正确显示:

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

我只想显示: 无效的凭据

【问题讨论】:

    标签: swift rawstring


    【解决方案1】:

    您可以为您的错误添加自定义类型并使其符合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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      • 2016-06-08
      相关资源
      最近更新 更多