简体   繁体   中英

Swift & macOS: Timer works with delay when app works in background

I have an macOS app that have timer and increase number every second. Every 60 second I show a notification with some message.

I found that my macOS Swift app runs with some delay, and after ~10 minutes started to sleep (no new a;lets appear anymore).

I have found some solutions, like this:

private func startTimer() {
    timer = Timer.scheduledTimer(
        timeInterval: 1.0,
        target: self,
        selector: #selector(timerTick),
        userInfo: nil,
        repeats: true
    )
    RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
}

But this command don't helped me to fix the lag with background run of timer: RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)

Need some experienced Swift guy who can help me to solve this interesting challenge. I need to count seconds in background app correctly, because my app shows alert messages every few minutes, and if it can't show me these alerts correctly - my app will work not as I expected.

Thank you!

My bet is that you're running into App Nap . You do have some control about telling the system your process should not be wound down with App Nap via NSProcessInfo .

You may also be able to try to disable App Nap defaults write <app domain name> NSAppSleepDisabled -bool YES ... but not sure if that still works or not (App Nap was introduced in OS X 10.9, so the three years time may have disabled the disable function...)

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