How can I reload new JSON data from the same site in Swift?

Viewed 116

basically i am making an app that pulls a number from online (using json) and what i want to know is how i can reload that data every 5 seconds or so. I have set it up so it is in a function called getData() and i thought making it in an infinite while loop would work like this: while 1 > 0 { getData() sleep(5) } However, whenever i launch the app it crashes. (It works when i call getData() without the infinite loop) Am i missing something? How can i refresh my json data every 5 seconds? Thank You!

1 Answers

Apart from these you can use:

var timerDispatchSourceTimer : DispatchSourceTimer?

you can call your function in ViewWillAppear and set the delay as you want:

timerDispatchSourceTimer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
timerDispatchSourceTimer?.scheduleRepeating(deadline: .now(), interval: .seconds(YOUR DELAY TIME))
timerDispatchSourceTimer?.setEventHandler{
            // do something here
  self.performSelector(inBackground: #selector(YOUR FUNCTION), with: nil)
        }
timerDispatchSourceTimer?.resume()

and on viewwillDisAppear:

timerDispatchSourceTimer?.cancel()
Related