Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a service call at regular interval of time in swift

Tags:

ios

swift

iphone

I am new to swift programming and I don't know how to call a method at regular interval of time. I have a demo app for service call but i don't know how can i call it at regular interval of time.

like image 748
Rishabh Srivastava Avatar asked Dec 01 '22 01:12

Rishabh Srivastava


2 Answers

You can create an object of NSTimer() and call a function on definite time interval like this:

var updateTimer = NSTimer.scheduledTimerWithTimeInterval(15.0, target: self, selector: "callFunction", userInfo: nil, repeats: true)

this will call callFunction() every 15 sec.

func callFunction(){
    print("function called")
}
like image 122
Ravi_Parmar Avatar answered Dec 22 '22 13:12

Ravi_Parmar


Here is a simple example with start and stop functions:

private let kTimeoutInSeconds:NSTimeInterval = 60

private var timer: NSTimer?

func startFetching() {
  self.timer = NSTimer.scheduledTimerWithTimeInterval(kTimeoutInSeconds,
    target:self,
    selector:Selector("fetch"),
    userInfo:nil,
    repeats:true)
}

func stopFetching() {
  self.timer!.invalidate()
}

func fetch() {
  println("Fetch called!")
}

If you get an unrecognized selector exception, make sure your class inherits from NSObject or else the timer's selector won't find the function!

like image 24
Zorayr Avatar answered Dec 22 '22 13:12

Zorayr