如何在Swift中从同一网站重新加载新的JSON数据?

问题描述:

基本上我正在制作一个应用程序,从网上(使用JSON)拉数字,我想知道的是如何我可以每5秒左右重新加载数据。我已经设置了它,所以它在一个名为getData()的函数中,我认为在一个无限的while循环中可以这样工作: while 1 > 0 { getData() sleep(5) } 但是,每当我启动应用程序时,它都会崩溃。 (它工作时,我没有无限循环调用getData())我错过了什么?我如何每5秒刷新一次json数据?谢谢!如何在Swift中从同一网站重新加载新的JSON数据?

+2

切勿使用'sleep()'或一个无限循环,否则会阻塞该线程。如果您必须进行轮询,请使用'Timer()' – Paulw11

+0

我将如何设置计时器?并会刷新数据? – Carter4502

+0

['Timer'](https://developer.apple.com/documentation/foundation/timer)在“滴答”时执行一个函数;您可以在该功能中重新加载数据。 – Paulw11

从这些

除了可以使用:

var timerDispatchSourceTimer : DispatchSourceTimer? 

你可以调用你的函数在viewWillAppear中,当你想设置的延迟:

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() 

和viewwillDisAppear:

timerDispatchSourceTimer?.cancel()