ios - 解析json数据后更新swiftui TextView

标签 ios swift swiftui swift5

我有一个函数可以发送到 api 并获取股票价格。我有返回 double 的函数,当我运行代码时,我可以看到正确的价格打印到控制台。当我尝试将该价格设置为函数内的变量以便函数可以返回它时,我在 TextView 中只得到 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
            }
        }

    }

}

关于ios - 解析json数据后更新swiftui TextView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59524951/

相关文章:

ios - Nil 与预期的参数类型 'String' 不兼容

php - Apple 推送通知的证书

ios - 在 Swift 中预览 iCarousel 中的 UIWebView

ios - 解析查询不起作用

ios - 在我的选项卡栏 View 中,我的 TableView 在启动时无法加载数据,但是当我点击离开并点击返回时数据会出现

iOS Swift 3 架构问题

ios - 键盘扩展中的preferredScreenEdgesDeferringSystemGestures不起作用

ios - 如何在设备屏幕因不活动而关闭时/之前立即执行方法?

ios - 是否可以从 struct 数组中获取一个项目,然后附加到 SwiftUI 中的不同数组?

SwiftUI tabview(滚动)事件?