解析 json 数据后更新 swiftui 文本视图
Updating swiftui text view after parsing json data
我有一个函数可以输出 api 并获取股票价格。我有函数 returning a double,当我 运行 代码时,我可以看到正确的价格打印到控制台。当我尝试将该价格设置为函数内的变量以便函数可以 return 时,我在文本视图中只得到 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
}
}
您可以通过更改 @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
}
}
}
}
我有一个函数可以输出 api 并获取股票价格。我有函数 returning a double,当我 运行 代码时,我可以看到正确的价格打印到控制台。当我尝试将该价格设置为函数内的变量以便函数可以 return 时,我在文本视图中只得到 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
}
}
您可以通过更改 @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
}
}
}
}