0

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!

Community
  • 1
  • 1
rocket101
  • 7,369
  • 11
  • 45
  • 64
  • 1
    Don't make it call view did load, use another method. What specifically are you struggling with? You understand the parameters? Read the docs? – Wain Aug 02 '14 at 15:29

1 Answers1

3

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.

codester
  • 36,891
  • 10
  • 74
  • 72
  • All my code is in viewdidload. It's a very simple app, and doesn't need to save anything before closing. As pretty much all viewdidload does is pull the data and display it, wouldn't it just be easier to call viewdidload? If so, how would I do that? – rocket101 Aug 02 '14 at 15:34
  • 1
    No `viewDidLoad` is lifecycle method you should not call it.Put all your code in `update` method from `viewDidLoad` and than call the update method in `viewDidLoad` explicitly and than start the timer.If you want to repeat timer every 3 minutes use 180 instead of 0.4 – codester Aug 02 '14 at 15:38
  • ok thanks. Now, does the update and timer function goes outside viewdidload, right? Or is it a function inside a function? Thanks, and sorry for my novice skills. – rocket101 Aug 02 '14 at 15:40