I have a case study here. In which I have a function named
loadData(action:String)
on viewDidLoad I am calling this function as loadData("sync") Now I want to recall this function as loadData("load") if its calling interval is inbetween 30 seconds. Lets say I want to call this function with "sync" if 30 seconds have been passed and if not then "load"
Please guide me.
There is one solution to use NSTimer
to count the seconds. and when you first call the loadData("sync")
method start the timer. and increment the second. and when you have to recall this function check the calculated seconds if it is > 30 then call sync
otherwise call load
. see the below code.
var timer : NSTimer!
var second = 0
override func viewDidLoad() {
super.viewDidLoad()
// here you start your first sync method.
loadData("sync")
// start the timer here so you can get how many seconds before you started or called your method.
timer = NSTimer()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.calculateSeconds), userInfo: nil, repeats: true)
}
func calculateSeconds() {
second += 1
}
now when you have to recall the loadData
method check the second variable that if it is > 30 then call sync
else load
. and invalidate
that timer to that the timer will stop monitoring or calculating the second.
Like this.
func whatever() {
if second > 30 {
loadData("sync")
} else {
loadData("load")
}
second = 0
timer.invalidate()
timer = nil
}