透過 Timer 設定每幾秒重複執行 function

(timer, scheduledTimer)

如果想固定每隔一段時間執行某個函式
可以參考本文

透過Timer來設定固定時間執行function

var timer = Timer() 
timer = Timer.scheduledTimer(timeInterval: , target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)

timeInterval: 時間區隔
timerAction: 執行的函式

執行的func函式

@objc func timerAction() {        
// execute change map setting
}

離開畫面時,停止timer計算
(否則timer會一直在背景執行)

override func viewWillDisappear(_ animated: Bool) { 
super.viewWillDisappear(animated)
timer.invalidate()
}

完成

完整code

--

--