【发布时间】:2020-04-17 09:35:34
【问题描述】:
如果这是一个愚蠢的问题,请提前道歉。我真的很陌生。
所以我正在尝试制作一个简单的应用程序,显示用户选择的特定货币的当前比特币价格。
首先我准备网址:
let baseURL = "https://api.coindesk.com/v1/bpi/currentprice/"
let currencyArray = ["AUD", "BRL","CAD","CNY","EUR","GBP","HKD","IDR","ILS","INR","JPY","MXN","NOK","NZD","PLN","RON","RUB","SEK","SGD","USD","ZAR"]
var finalURL = ""
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
finalURL = baseURL + currencyArray[row]
coinSelected = currencyArray[row]
getBitcoinData(url: finalURL)
}
然后我得到 JSON 数据。
Alamofire.request(url, method: .get)
.responseJSON { response in
if response.result.isSuccess {
let bitcoinJSON = JSON(response.result.value!)
print bitcoinJSON
到目前为止一切顺利,我得到了我的 JSON 数据并且打印正确。
{
"time": {
"updated": "Apr 17, 2020 08:39:00 UTC",
"updatedISO": "2020-04-17T08:39:00+00:00",
"updateduk": "Apr 17, 2020 at 09:39 BST"
},
"disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
"bpi": {
"USD": {
"code": "USD",
"rate": "7,074.9583",
"description": "United States Dollar",
"rate_float": 7074.9583
},
"GBP": {
"code": "GBP",
"rate": "5,687.3185",
"description": "British Pound Sterling",
"rate_float": 5687.3185
}
}
}
我接下来要做的是获取 GBP 的汇率。 (不知何故,美元汇率总是显示在我选择的货币之前)
我尝试做的是:
func updateBitcoinData(json : JSON) {
let bitcoinRATE = json ["bpi"][1]["rate"]
print(bitcoinVALUE)
}
但它总是返回 nil...
【问题讨论】:
-
json ["bpi"]是字典,而不是数组,所以json ["bpi"][1]没有意义。执行json ["bpi"]["USD"]或json ["bpi"]["GBP"]可以。 -
@Larme,您为什么将答案作为评论发布?将其作为答案发布,以便被接受。
-
但是我该如何选择美元之后的货币呢?我不能只做 json ["bpi"]["GBP"] 因为货币总是不同的。这就是为什么我试图指定 [1] 来表示“选择第二个值”...
-
你没有。这是字典与数组。访问数据的两种不同逻辑。一种是按索引(有序),另一种是按键(无序)。它首先打印美元,由于某些未知原因,明天可能会发生变化,数据将是相同的。
-
json 字典不保证顺序,您可以在这里阅读更多内容:stackoverflow.com/questions/42290866/ordered-dictionary-in-json