我正在尝试使用适用于 iOS 的 Alpha Vantage API 构建一个显示货币汇率的应用程序。我已经构建了函数,但无法弄清楚如何访问确切的 json 值,即“5. Exchange Rate”。
以下是一些代码和 json 数据,以帮助更好地解释:
建立的网址:
func USDtoEUR(_ completionHandler: @escaping (_ success: Bool, _ quotes: [String:AnyObject]?, _ error: String?) -> Void) {
let urlString = "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=USD&to_currency=EUR&apikey=NP3M8LL62YJDO0YX"
let session = URLSession.shared
let url = URL(string: urlString)!
let request = URLRequest(url: url)
let task = session.dataTask(with: request, completionHandler: { data, response, error in
if error != nil {
completionHandler(false, nil, error!.localizedDescription)
}
else {
do {
let result = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
if let dictionary = result["Realtime Currency Exchange Rate"] as? [String:AnyObject]! {
completionHandler(true, dictionary, nil)
}
else {
completionHandler(false, nil, nil)
}
} catch {
completionHandler(false, nil, "Unable to process retrieved data.")
}
}
})
task.resume()
}
视图控制器中的引号
func usdQUotesRequest() {
USDClient().USDtoEUR() { success, newQuote, error in
if success {
self.usdtoeurquote = newQuote
DispatchQueue.main.async {
self.stopActivityIndicator()
self.Refresh.isEnabled = true
}
} else {
DispatchQueue.main.async {
self.displayAlert("Unable to Retrieve Latest Conversion Rates", message: "\(error!)")
self.stopActivityIndicator()
self.Refresh.isEnabled = true
}
}
}
// 触摸美元按钮后显示的报价:
@IBAction func usdConversions(_ sender: Any) {
self.displayAlert("Alert!", message: "USD Selected")
let usdVal = (outputCurrency1.text! as NSString).floatValue
let euroValue = usdVal * (usdtoeurquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", euroValue)
let gbpVal = usdVal * (usdtogbpquote["5. Exchange Rate"] as! Float)
outputCurrency3.text = String(format: "%.2f", gbpVal)
let cnyVal = usdVal * (usdtocnyquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", cnyVal)
let cadVal = usdVal * (usdtocadquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", cadVal)
let inrVal = usdVal * (usdtoinrquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", inrVal)
let sekVal = usdVal * (usdtosekquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", sekVal)
let rubVal = usdVal * (usdtorubquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", rubVal)
let nzdVal = usdVal * (usdtonzdquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", nzdVal)
}
The Raw JSON Data:网页上的 json 数据