gpt4 book ai didi

ios - 解码 API 数据

转载 作者:搜寻专家 更新时间:2023-11-01 06:14:10 25 4
gpt4 key购买 nike

我正在尝试从 API 获取数据,但无法正确获取,我不知道这里的问题:

struct BTCData : Codable {
let close : Double
let high : Double
let low : Double

private enum CodingKeys : Int, CodingKey {
case close = 3
case high = 4
case low = 5
}
}

func fetchBitcoinData(completion: @escaping (BTCData?, Error?) -> Void) {
let url = URL(string: "https://api.bitfinex.com/v2/candles/trade:30m:tBTCUSD/hist")!

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
do {
if let bitcoin = try JSONDecoder().decode([BTCData].self, from: data).first {
print(bitcoin)
completion(bitcoin, nil)
}
} catch {
print(error)
}
}
task.resume()
}

我希望能够在每个 dict 中访问 close 并像这样迭代:

var items : BTCData!

for idx in 0..<15 {
let diff = items[idx + 1].close - items[idx].close
upwardMovements.append(max(diff, 0))
downwardMovements.append(max(-diff, 0))
}

我得到 nil。我不明白如何解码这种 API,我需要迭代不在另一个 dict 中的东西。

编辑:以上问题已解决,我现在正努力在另一个函数中使用 [BTCData]。

我在这里尝试使用它:

func fetchBitcoinData(completion: @escaping ([BTCData]?, Error?) -> Void) {

let url = URL(string: "https://api.bitfinex.com/v2/candles/trade:30m:tBTCUSD/hist")!

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {
completion(nil, error ?? FetchError.unknownNetworkError)
return
}
do {
let bitcoin = try JSONDecoder().decode([BTCData].self, from: data); completion(bitcoin, nil)
//let close52 = bitcoin[51].close
//print(bitcoin)
//print(close52)
} catch let parseError {
completion(nil, parseError)
}
}
task.resume()
}
class FindArray {

var items = [BTCData]()

func findArray() {
let close2 = items[1].close
print(close2)
}
}

fetchBitcoinData() { items, error in
guard let items = items,
error == nil else {
print(error ?? "Unknown error")
return
}
let call = FindArray()
call.items = items
call.findArray()
}

编辑 2:使用 [BTCData]() 解决。 var items : [BTCData] = [] 也有效

最佳答案

要使用 Decodable 将数组数组解码为结构,您必须使用 unkeyedContainer。由于没有字典,CodingKeys 没有用。

struct BTCData : Decodable {
let timestamp : Int
let open, close, high, low, volume : Double

init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
timestamp = try container.decode(Int.self)
open = try container.decode(Double.self)
close = try container.decode(Double.self)
high = try container.decode(Double.self)
low = try container.decode(Double.self)
volume = try container.decode(Double.self)
}
}

您不必更改 JSONDecoder() 行。

...
if let bitcoin = try JSONDecoder().decode([BTCData].self, from: data).first {
print(bitcoin)
completion(bitcoin, nil)
}

只需添加两行,甚至可以将时间戳解码为Date

struct BTCData : Decodable {
let timestamp : Date
let open, close, high, low, volume : Double

init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
timestamp = try container.decode(Date.self)
...

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .millisecondsSince1970
if let bitcoin = try decoder.decode([BTCData].self, from: data).first {
print(bitcoin)
completion(bitcoin, nil)
}

解码数组并获取特定索引处的值

do {
let bitcoins = try JSONDecoder().decode([BTCData].self, from: data)
let close52 = bitcoins[51].close
print(close52)
...

关于ios - 解码 API 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48619230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com