Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

swift - Pass variable from function to view

I have some variables that I want to pass to a ContentView.

This is the Data.swift file with the class and function that fetch the variables:

import SwiftUI

class Api {
    
    func getValues() {
        
        let url = URL(string: "URL")
        guard let requestUrl = url else { fatalError() }

        var request = URLRequest(url: requestUrl)
        request.httpMethod = "GET"
        request.setValue("User Agent", forHTTPHeaderField: "User-Agent")
        request.setValue("Auth", forHTTPHeaderField: "Authorization")

        URLSession.shared.dataTask(with: request) { (data, _, _) in
            
            let dataString = String(data: data!, encoding: .utf8)
  
            func convertToDictionary(text: String) -> [String: Any]? {
                if let data = text.data(using: .utf8) {
                    do {
                        return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
                    } catch {
                        print(error.localizedDescription)
                    }
                }
                return nil
            }
          
            let dict = convertToDictionary(text: dataString!)
            let array = dict!["array1"] as? NSArray
            let array0 = array![0] as? NSDictionary
            let id = array0!["id"] as! String
            let objects = array0!["object"] as! NSDictionary
            var total = 0
            var i = 0
            for object in objects {
                let key = object.key as! String
                let tmpDict = objects[(key)] as! NSDictionary
                let tmpStr = tmpDict["raw_value"] as! String
                let tmpD = Double(tmpStr)
                let value = Int(tmpD!)
                print(value)
                total+=value
                i+=1
                }
            print("ID: (id)")
            let fractionalProgress = CGFloat(total / i)/6
            let roundedProgress = CGFloat(round(100*fractionalProgress)/100)
            print("Average value: (roundedProgress)")
        }
        .resume()
    }
}

For the sake of simplicity, I have included a part of the JSON I'm working with below:

{
  "array1": [
    {
      "link_id": 1,
      "object": {
        "2000000000007522336": {
          "is_draft": 0,
          "value": "4",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "4.00",
          "numerical_value": null
        },
        "2000000000016619051": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        }
      },
      "deleted_at": null,
      "id": "1_20",
      "status_id": 1,
      "target_num": 1
    },
    {
      "link_id": 55,
      "object": {
        "2000000000010046787": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        },
        "2000000000005323660": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        },
        "2000000000006311217": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        },
        "2000000000011929948": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        },
        "2000000000004856132": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        },
        "2000000000007455406": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        },
        "2000000000009846642": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        },
        "2000000000016910392": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        },
        "2000000000014735487": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        }
      },
      "deleted_at": null,
      "id": "55_20",
      "status_id": 1,
      "target_num": 2
    },
    {
      "link_id": 2,
      "object": {
        "2000000000012123534": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        },
        "2000000000004686641": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        },
        "2000000000006918209": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        },
        "2000000000007310987": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        },
        "2000000000013890209": {
          "is_draft": 0,
          "value": "6",
          "show_text": null,
          "show_icon_mobile": null,
          "raw_value": "6.00",
          "numerical_value": null
        }
      },
      "deleted_at": null,
      "id": "2_20",
      "status_id": 1,
      "target_num": 3
    }
  ]
}

Here's the ContentView:

import SwiftUI

struct ContentView: View {
    @State var show = false
    var body: some View {
        Text("Hello, world!")
            .onAppear() {
                Api().getValues()
            }
        Text("Values should appear here.")
        Circle()
            .trim(from: show ? "roundedProgress CGFloat" : 0.99, to: 1)
            .stroke(Color.green, style: StrokeStyle(lineWidth: 7.5, lineCap: .round, lineJoin: .round))
            .rotationEffect(.degrees(90))
            .rotation3DEffect(Angle(degrees: 180), axis: (x: 1, y: 0, z: 0))
            .frame(width: 100, height: 100)
            .animation(.easeOut)
            .onAppear() {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
                    self.show.toggle()
                }
            }
        }
    }

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Ideally, I want to trim the ring view based on the roundedProgress float's value and display the values in the text action after the onAppear().

I tried putting the entire function in the onAppear() action but nothing changed. Putting the code without onAppear() shows an error "Failed to produce diagnostic for expression; please file a bug report" on the URLSession action I have for fetching the data.

question from:https://stackoverflow.com/questions/65847928/pass-variable-from-function-to-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...