【问题标题】:Having issue converting response in UTF-8 format以 UTF-8 格式转换响应时出现问题
【发布时间】:2019-05-29 06:24:11
【问题描述】:

我收到此行的错误:

Data(from: responseValue.utf8 as! Decoder)

)

无法将“数据”类型的值转换为预期的参数类型“数据”

do{
    let responseData = try JSONDecoder().decode(forget_Base.self, from: Data(from: responseValue.utf8 as! Decoder))
    if responseData.code == 200
    {
        let message = isNilValue(assignValue: responseData.message)
        let alert = UIAlertController(title: "", message: message, preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: .default, handler: {(_action) -> Void in
            let next = self.storyboard?.instantiateViewController(withIdentifier: "SetPasswordVCSID")
            self.navigationController?.pushViewController(next!, animated: true)
        })
        alert.addAction(action)
        self.present(alert, animated: true, completion: nil)
    }
    else
    {
    }
}
catch
{
    print("error")
}

我该如何解决?我已经尝试了太多东西,但我还是坚持了下来。

【问题讨论】:

  • 这是什么魔法:responseValue.utf8 as! Decoder?如果你只使用responseValue会有什么结果?
  • 什么是responseValue
  • @JoakimDanielson 从 API 获取响应
  • @Lu_ 我没有得到任何响应,因为我附上了屏幕截图,因为错误没有编译。请检查
  • 我的意思是,它是什么类型的?如果它已经是数据,那么我假设你不需要对它做任何事情。

标签: ios swift encoding decode


【解决方案1】:

根据错误信息很简单

let responseData = try JSONDecoder().decode(forget_Base.self, from: Data(responseValue.utf8))

无论如何,转换为Decoder 的类型毫无意义。

并且请遵守命名约定,forget_Base 太可怕了,命名为ForgetBase

【讨论】:

  • 尝试并收到此错误-----(无法将“字符串”类型的值转换为预期的参数类型“数据”)
  • 那么它是Data(responseValue.utf8)。我更新了答案。
【解决方案2】:

按原样使用 responseValue。 这是代码: 更改以下内容

let responseData = try JSONDecoder().decode(forget_Base.self, from: Data(from: responseValue.utf8 as! Decoder))

let responseData = try JSONDecoder().decode(forget_Base.self, from:responseValue)

【讨论】:

  • 你是对的。我应该只调整有关的行。我的错!根据您的建议编辑@JoakimDanielson
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 2013-02-25
相关资源
最近更新 更多