【问题标题】:Updating swiftui text view after parsing json data解析json数据后更新swiftui文本视图
【发布时间】:2019-12-30 02:09:00
【问题描述】:

我有一个函数可以发送到 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
       }

}

【问题讨论】:

    标签: ios swift swiftui swift5


    【解决方案1】:

    您可以通过更改 @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
                }
            }
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 2020-06-30
      • 2023-01-12
      相关资源
      最近更新 更多