简体   繁体   中英

NSTimer not firing after home button is pressed

II have an NSTimer set to fire each second. Using the Simulator this will call the eachSecond() method correctly after I navigate away from the app by pressing the home button. However, on a real iPhone 6, once I navigate away eachSeconds is not called again until the app is open again.

Why might this behave differently on a real device? Is there anyway to ensure it will fire each second in this use case?

Its a fitness app, so needs to record duration when the phone locks or user navigates away momentarily.

Thanks,

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.
}

An NSTimer will not fire when your app is suspended. Background execution is different when running under XCode; background execution limits do not apply.

In order to determine how much time has elapsed while your app is suspended, you can store a timestamp in applicationDidEnterBackground and calculate the elapsed time based on the difference between the saved timestamp and current time in applicationWillEnterForeground

You need to add the timer to the main run loop.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM