0

im trying to fetch some data from a Http Api and use the responded JSON to update the text in my SwiftUI view accordingly

The problem is, that I need to fetch the data two times per second and I don't really know how to refresh my view accordingly.

This is how I fetch the data

var timer = Timer()
func scheduleTimer()             
  timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(fetchData), userInfo: nil, repeats: true)
    }

    @objc func fetchData() {
        let url:URL = URL(string: "http://XXX.XXX.XXX.23:8085/telemachus/datalink?altitude=v.altitude&longitude=v.long&latitude=v.lat&name=v.name")!
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let error = error { print(error) }
            guard let data = data else {return}

            do {
                let jsonData = try  JSONDecoder().decode(JsonData.self, from: data)
                let altitude = jsonData.altitude
                print(altitude)
            } catch let error {
                print(error)
            }
        }.resume()
    }

I used a timer to repeat this action. I also have a Model for the JsonData. @EnvironmentObject is not usable in this case because the function is not inside the view.

nOk
  • 2,725
  • 4
  • 13
  • 26

1 Answers1

1

First of all, This will kill the battery very quick. Also it may kill the bandwidth and the user may be blocked for too many requests.

Second of all, you should use socket for these kind of requests instead of restful.

Third of all your answer:

Two times per second? change the timeInterval value to 0.5. This will cause the execution to perform each half of second.

To update UI, you need to perform the update code in the main thread using the GCD or Operation queue like this:

DispatchQueue.main.async {
    /* UI Work Goes Here */
    // for example: myLabel.text = jsonData.altitude
}
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
  • I know about the battery drain. The app is more like a personal project for a Kerbal Space Program Nerd, that wants to control his rockets with his iPad xD) The problem I had about updating the UI was that I haven't found out how to do it while the function doesn't run from the view but in the background and I can't access it's variables from said function – nOk Aug 03 '19 at 12:15
  • I was asking for a general solution. I don't really have UI Code because I don't know how to deliver data from my function to the view – nOk Aug 04 '19 at 20:16
  • I tried using socket but it keeps disconnecting to the Websocket. [link] (https://stackoverflow.com/questions/57373637/websocket-keeps-disconnecting-starscream) – nOk Aug 06 '19 at 10:16
  • I answered there. But that is a different question. Please don't forget to upvote. And accept as answer to **this** question if you find it as an answer. Feel free to ask any further questions. – Mojtaba Hosseini Aug 06 '19 at 10:22
  • I though you are looking for *a general solution*. If you need a specific solution, please update your question with the example of the code you tried. I will help surely. – Mojtaba Hosseini Aug 06 '19 at 11:07
  • Oh sorry I tagged swiftUI but then forgot to put it in the title. My problem was that I can't refresh a swiftUI view in DispatchQueue – nOk Aug 09 '19 at 14:27