Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 按下home(主页)按钮后,N定时器未触发_Ios_Swift_Nstimer - Fatal编程技术网

Ios 按下home(主页)按钮后,N定时器未触发

Ios 按下home(主页)按钮后,N定时器未触发,ios,swift,nstimer,Ios,Swift,Nstimer,我有一个NSTimer设置为每秒开火。使用模拟器,在按下home按钮离开应用程序后,将正确调用eachSecond()方法。然而,在真正的iPhone6上,一旦我离开,每隔几秒钟都不会被再次调用,直到应用程序再次打开 为什么在真正的设备上会有不同的行为?在这个用例中,是否有任何方法可以确保它每秒都会启动 这是一款健身应用程序,因此需要记录手机锁定或用户暂时离开时的持续时间 谢谢 lazy var timer = NSTimer() fun init() { timer = NSTimer

我有一个NSTimer设置为每秒开火。使用模拟器,在按下home按钮离开应用程序后,将正确调用eachSecond()方法。然而,在真正的iPhone6上,一旦我离开,每隔几秒钟都不会被再次调用,直到应用程序再次打开

为什么在真正的设备上会有不同的行为?在这个用例中,是否有任何方法可以确保它每秒都会启动

这是一款健身应用程序,因此需要记录手机锁定或用户暂时离开时的持续时间

谢谢

lazy var timer = NSTimer()

fun init() {
   timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(RunViewController.eachSecond(_:)), userInfo: nil, repeats: true)
}

func eachSecond() {
 // update UI etc.
}

您需要将计时器添加到主运行循环中

func init() {
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(RunViewController.eachSecond(_:)), userInfo: nil, repeats: true)

    NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}

您需要将计时器添加到主运行循环中

func init() {
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(RunViewController.eachSecond(_:)), userInfo: nil, repeats: true)

    NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}

当应用程序挂起时,
n计时器
不会启动。在XCode下运行时后台执行不同;后台执行限制不适用


为了确定应用程序挂起时经过的时间,您可以在
applicationIdentinterbackground
中存储时间戳,并根据
applicationWillEnterForeground
中保存的时间戳和当前时间之间的差异计算经过的时间。当您的应用程序挂起时,
NSTimer
将不会触发。在XCode下运行时后台执行不同;后台执行限制不适用


为了确定应用程序挂起时经过的时间,您可以在
applicationIdentiterBackground
中存储时间戳,并根据
applicationWillEnterForeground

中保存的时间戳和当前时间之间的差值计算经过的时间
scheduledTimerWithTimeInterval
函数已将计时器添加到运行循环中
scheduledTimerWithTimeInterval
函数已将计时器添加到运行循环中。