下面的代码从API访问最新数据,并将其存储在相应的结构中。
我现在需要访问前4天并存储它们,但是我不知道从哪里开始访问数据结构,或者甚至有可能在不将信息保存到数据库以供以后访问的情况下进行访问。
struct Root: Codable {
let metaData: [String: String]
let timeSeriesFX5Min: [String:Forex]
enum CodingKeys: String, CodingKey {
case timeSeriesFX5Min = "Time Series FX (DAILY)"
case metaData = "Meta Data"
}
}
// MARK: - TimeSeriesFX5Min
struct Forex: Codable {
let open, high, low, close: String
enum CodingKeys: String, CodingKey {
case open = "1. open"
case high = "2. high"
case low = "3. low"
case close = "4. close"
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let jsonUrlString = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo"
let urlObj = URL(string: jsonUrlString)
URLSession.shared.dataTask(with: urlObj!) {(data, response, error) in
guard let data = data else { return }
do {
let forex = try JSONDecoder().decode(Root.self, from: data)
print(forex.metaData)
if let latestTime = forex.metaData["4. Last Refreshed"], let latestForex = forex.timeSeriesFX5Min[latestTime] {
}
} catch {
print(error)
}
}.resume()
}
}
答案 0 :(得分:0)
getGenericSuperclass
(更好的Class
)的密钥是timeSeriesFX5Min
。
timeSeriesDaily
过滤最近的4个条目的最简单方法是获取键,对它们进行降序排序,然后从字典中提取给定键的前4个值
"Time Series (Daily)"