【问题标题】:SwiftUI URLSession error when fetching data (typeMismatch) WEBAPI获取数据时的SwiftUI URLSession错误(typeMismatch)WEBAPI
【发布时间】:2020-02-01 23:49:50
【问题描述】:

一旦我按下按钮并调用函数,我试图从 url 获取数据,但是一旦调用函数,我就会不断收到 typeMismatch 错误。

这是我的代码:

struct User: Decodable {
    var symbol: String
    var price: Double
}

struct Response: Decodable {
    var results:[User]
}


struct ContentView: View {
    var body: some View {
        VStack {
            Text("hello")
            Button(action: {
                self.fetchUsers(amount: 0)
            }) {
                Text("Button")
            }
        }

    }

    func fetchUsers(amount: Int) {
        let url:URL = URL(string: "https://api.binance.com/api/v3/ticker/price")!

        URLSession.shared.dataTask(with: url) { (data, res, err) in
            if let err = err { print(err) }
            guard let data = data else { return }
            do {
                let response = try JSONDecoder().decode(Response.self, from: data)
                print(response.results[0])
            } catch let err {
                print(err)
            }
        }.resume()
    }

}

这是错误:

typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

我试图从中获取数据的网站网址是: https://api.binance.com/api/v3/ticker/price

我试图从特定符号中获取特定价格,例如 ETHBTC 的价格,即 0.019...

谢谢

【问题讨论】:

    标签: swiftui xcode11 swift5 type-mismatch urlsession


    【解决方案1】:

    这种方法有两个错误。首先,如果您使用

    创建了一个 Response 结构
    results = [User]
    

    这样,您希望 json 采用 [result: {}] 的形式,但您的 [{}] 格式在开始时没有名称。所以你应该用

    替换响应结构
    typealias Response = [User]
    

    您使用的所有 API 中的第二个是返回字符串而不是作为价格的两倍,因此您应该将您的结构修改为:

    struct User: Decodable {
        var symbol: String
        var price: String
    }
    

    这种方式对我有用。测试下

    • 斯威夫特 5
    • xcode 11.3.1
    • iOS 13.3.1 非测试版

    【讨论】:

      猜你喜欢
      • 2022-09-22
      • 2023-03-24
      • 2021-07-30
      • 2017-07-26
      • 1970-01-01
      • 2022-10-08
      • 1970-01-01
      • 2017-03-13
      • 2021-03-08
      相关资源
      最近更新 更多