In Swift, I am writing a simple first app. As it is not complex at all, nearly all code that is used happens in the viewDidLoad method. However, the app deals with live data (the bitcoin price, to be exact). I would like the app to re-fetch the price every 3 minutes, to that the price stays current.
var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
I used the code above, which I got from the top answer of This stackoverflow question. However, how can I make it run viewDidLoad after 3 minutes? I don't understand how it calls functions. As all the code, including updating, is in viewDidLoad, that is all I need to be called.
Let me know if you need more info. Thanks!
The timer repeats:
set to true
so it will automatically repeat after 0.4 sec
and will call your update
method implementation.If you want to call update
method immediately than explicitly call update
method in viewDidLoad
and start the timer
Refer NSTimer
documentation.
You do not need to call and should not call viewDidLoad
again
override func viewDidLoad() {
self.update(); //it will call update immediately
var timer = NSTimer.scheduledTimerWithTimeInterval(180, target: self, selector: Selector("update"), userInfo: nil, repeats: true) //repeats after 3minutes
}
func update() {
//Your all code which is in viewDidLoad
}
if you want to update something it in update
method so after 180 i.e 3minutes
it will automatically fetch your data and refreh the UI.