2017-11-11 52 views
3

基本上我正在製作一個應用程序,從網上(使用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

回答

1
從這些

除了可以使用:

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() 
相關問題