在swift中定期拨打服务电话

Ris*_*ava 4 iphone ios swift

我是快速编程的新手,我不知道如何定期调用方法.我有一个服务电话的演示应用程序,但我不知道如何定期调用它.

Rav*_*mar 14

你可以创建一个NSTimer()的对象,并在一定的时间间隔内调用一个函数,如下所示:

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

这将每15秒调用一次callFunction().

func callFunction(){
    print("function called")
}
Run Code Online (Sandbox Code Playgroud)


Zor*_*ayr 5

这是一个带启动和停止功能的简单示例:

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!")
}
Run Code Online (Sandbox Code Playgroud)

如果出现unrecognized selector异常,请确保您的类继承自NSObject,否则计时器的选择器将找不到该函数!