【发布时间】:2018-06-21 04:55:04
【问题描述】:
是否可以通过相同的结构从不同但相似的 API(不同的 URL 但相似的 JSON 结构)获取数据?
例如通过bitcoinUSD.raw.eth.usd.price和bitcoinUSD.raw.eth.gbp.price访问数据:
struct Bitcoin : Decodable {
private enum CodingKeys : String, CodingKey { case raw = "RAW" }
let raw : BitcoinRAW
}
struct BitcoinRAW : Decodable {
private enum CodingKeys : String, CodingKey { case btc = "BTC" }
let btc : BitcoinETH
}
struct BitcoinETH : Decodable {
private enum CodingKeys : String, CodingKey {
case usd = "USD"
case gbp = "GBP"
}
let usd : BitcoinUSD
let gbp : BitcoinGBP
}
struct BitcoinUSD : Decodable {
let price : Double
let percentChange24h : Double
private enum CodingKeys : String, CodingKey {
case price = "PRICE"
case percentChange24h = "CHANGEPCT24HOUR"
}
}
struct BitcoinGBP : Decodable {
let price : Double
let percentChange24h : Double
private enum CodingKeys : String, CodingKey {
case price = "PRICE"
case percentChange24h = "CHANGEPCT24HOUR"
}
}
这是我的数据获取函数:
enum MyErrorBTC : Error {
case FoundNil(String)
}
class BitcoinInfo : NSObject {
static var btcURL : URL?
func fetchBitcoinInfo(completion: @escaping (Bitcoin?, Error?) -> Void) {
if WalletViewController.currencyUSD == true {
BitcoinInfo.btcURL = URL(string: "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC&tsyms=USD")!
let task = URLSession.shared.dataTask(with: BitcoinInfo.btcURL!) { (data, response, error) in
guard let data = data else { return }
do {
if let bitcoinPrice = try? JSONDecoder().decode(Bitcoin.self, from: data) {
completion(bitcoinPrice, nil)
//print("price =", bitcoinUSD.raw.btc.usd.price)
throw MyErrorBTC.FoundNil("bitcoinPrice")
}
} catch {
print(error)
}
}
task.resume()
} else if WalletViewController.currencyGBP == true {
BitcoinInfo.btcURL = URL(string: "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC&tsyms=GBP")!
let task = URLSession.shared.dataTask(with: BitcoinInfo.btcURL!) { (data, response, error) in
guard let data = data else { return }
do {
if let bitcoinPrice = try? JSONDecoder().decode(Bitcoin.self, from: data) {
completion(bitcoinPrice, nil)
//print("price =", bitcoinUSD.raw.btc.gbp.price)
throw MyErrorBTC.FoundNil("bitcoinPrice")
}
} catch {
print(error)
}
}
task.resume()
}
}
}
请注意,当调用任一函数时,此代码返回 nil。 有什么办法可以修改吗?
【问题讨论】:
-
显示您的 API 获取函数,以便人们提供反馈。
-
@creeperspeak 我用完整代码编辑了我的问题