0

I'm using Swift 4 and Xcode 9.2 to build a timer app and I'm running into issues with macOS App Nap. I know that the issues are caused by App Nap since when I disable App Nap globally the issues go away. However I only want to disable App Nap for this particular app when I need to for it to run properly. I know that similar questions have been answered before and I have seen them, but either I don't understand how to use them in my case or they do not work anymore (possibly because of changes to the Swift language). Here is a small example of code that produces the issues I'm having:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    var timer = Timer()
    var seconds = 300

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

    @IBAction func goButton(_ sender: NSButton) {
        if !timer.isValid {
            timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AppDelegate.ticker), userInfo: nil, repeats: true)
        }
    }

    @objc func ticker() {
        seconds -= 1
        if seconds == 0 {
            timer.invalidate()
            print("Timer Ended.")
        }
    }
}

Any help is greatly appreciated.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    Which solutions did you try that "do not work anymore"? What "issues" does App Nap cause in your application? – Martin R Jan 19 '18 at 08:27
  • I tried these: https://stackoverflow.com/questions/35679066/disable-app-nap/35679299#35679299 https://stackoverflow.com/questions/27653939/disable-app-nap-in-swift – Vincent Pfenninger Jan 19 '18 at 08:54
  • 1
    The code from the first link compiles in Swift 4, the problem is not caused by "changes in the Swift language". – Martin R Jan 19 '18 at 08:57
  • The issue is simply that the timer sometimes stops running when the app is in the background. For example I noticed that when the app is running in the background and I watch a video on iTunes in full screen, then the timer stops running after about 3 to 5 minutes. – Vincent Pfenninger Jan 19 '18 at 08:57
  • I said it might also be that I just don't understand how to use the solutions in my case. (I'm very new to programming with Swift.) I know that with some solution I tried Xcode kept telling me "X is now called Y" and after I changed it Xcode would still not accept the code. – Vincent Pfenninger Jan 19 '18 at 09:01
  • I was able to prevent app napping by wrapping the code from the first link around "seconds -= 1" in my code. But when I start the timer there is a lag of about 2 to 3 seconds. Is there any way to fix that? – Vincent Pfenninger Jan 19 '18 at 12:01

0 Answers0