函数不是从swift中的NSTimer选择器调用(在模拟器中工作但在设备中没有)

时间:2015-10-13 11:09:48

标签: ios swift nstimer

我想检查一下我的应用程序可以在后台停留多少时间。所以我使用此代码管理它

func applicationDidEnterBackground(application: UIApplication) {
   print("entered in background")
   let timer = NSTimer.scheduledTimerWithTimeInterval(60 * 5, target: self, selector: "update", userInfo: nil, repeats: true)
   timer.fire()
}

我的更新功能

func update(){ 
   print("func call")
}

所有这些代码都可以在模拟器中运行,但每当我在设备中运行我的项目时,它都没有调用此功能。
当前台应用程序检查正确的计时器工作时,此功能也可以工作。还有功能调用 我正在使用swift 2.0 可能应用所有解决方案但没有成功。

修改
同时应用此代码

NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector(update()), userInfo: nil, repeats: true)

但它只是第一次调用函数

2 个答案:

答案 0 :(得分:1)

当您的应用程序进入后台时,将无法保证定时器将会触发。您可能需要一段时间才能暂停iOS的任务,但有时您无法获得任何操作,例如当设备被锁定时。 如果您想在后台运行,您需要查看Background Mode Execution

答案 1 :(得分:0)

你是否试过像这样声明你的方法:

func update(sender: NSTimer?) -> Void { 
    print("func call")
}

并确保你这样称呼它(注意分号:

func applicationDidEnterBackground(application: UIApplication) {
    print("entered in background")
    let timer = NSTimer.scheduledTimerWithTimeInterval(60 * 5, target: self, selector: "update:", userInfo: nil, repeats: true)
   timer.fire()
}