我有一个可以访问api并获取股票价格的函数。我有返回双精度值的函数,运行代码时可以看到正确的价格打印到控制台。当我尝试将价格设置为函数内部的变量以便函数可以返回价格时,我在文本视图中仅获得0.000。有人可以告诉我我在做什么错吗?我的代码在下面。
import SwiftUI
struct ListView: View {
var body: some View {
List {
HStack {
Text("Stock Price (15 Min. delay)")
Spacer()
Text("\(getStockPrice(stock: symbol))")
}
}
}
func getStockPrice(stock: String) -> Double {
var thePrice = Double()
guard let url = URL(string: "my url to get data") else {
fatalError("URL does not work!")
}
URLSession.shared.dataTask(with: url) { jsonData, _, _ in
guard let jData = jsonData else {return}
do {
if let json = try JSONSerialization.jsonObject(with: jData, options: []) as? [String: Any] {
if let pricer = json["latestPrice"] as? Double {
print(pricer)
thePrice = pricer
}
}
} catch let err {
print(err.localizedDescription)
}
}.resume()
return thePrice
}
}
答案 0 :(得分:0)
您可以通过更改@State
变量来更新UI,如下面的代码所示:
struct UpdatingPriceAsync: View {
@State var stockPrice: Double = 0.0
var body: some View {
List {
HStack {
Text("Stock Price (15 Min. delay)")
Spacer()
Text("\(stockPrice)")
.onAppear() {
self.updateStockPrice(stock: "something")
}
}
}
}
private func updateStockPrice(stock: String) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { // sort of URL session task
DispatchQueue.main.async { // you need to update it in main thread!
self.stockPrice = 99.9
}
}
}
}