NSTimer does not fire when NSMenu is open in Swift

I have a timer that starts to restart the alarm after it is turned off.

alarm = NSTimer.scheduledTimerWithTimeInterval( 60 * minutesConstant + secondsConstant, target:self, selector: Selector("endSession"), userInfo: nil, repeats:false) 

Its selection function sets the mode flag and calls the original function, which sets the alarm with new constants of minutes and seconds, and also sends a notification to the user about the restart of the session.

I have a menu item that updates with the remaining time

enter image description here

So, I open it to check that my alarm has really rebooted, and that the notification shows when it has reached zero. It works, but when I have a menu open and it drops to zero, it just stays at 0:00, and the timer does not work until I exit the menu, after which it immediately displays a notification and resets the timer, as expected

How can I make the timer light up when the menu is open? It doesn’t matter, but I don’t want the user to be confused with the session, it just hangs if they watch the timer go down.

+6
source share
1 answer

You just need to add your timer to the main runloop as follows:

Swift 3

 RunLoop.main.add(alarm, forMode: .commonModes) 

Swift 2.x

 NSRunLoop.mainRunLoop().addTimer(alarm, forMode: NSRunLoopCommonModes) 
+17
source

Source: https://habr.com/ru/post/981142/


All Articles