macosnsalert

how to close NSAlert after some time if no button is clicked by user


I want to close a alert Window (NSAlert) after specific period of time if user does not click on any of the buttons. Is there a way to set up a NSTimer to close the Alert Panel after some time, say 30 sec.


Solution

  • I just done something like that. I revised some of my codes for you here:

    class ViewController: NSViewController {
    
        var progressWindow:NSAlert!
    
        func testOfProgressWindow() {
            progressWindow = NSAlert()
            progressWindow.alertStyle = .InformationalAlertStyle
            progressWindow.messageText = "some notes"
    
            let date = NSDate(timeInterval: 30, sinceDate: NSDate())
            let uiUpdateTimer = NSTimer(fireDate: date, interval: 0, target: self, selector: "closeSheet", userInfo: nil, repeats: false)
            let runLoop = NSRunLoop.mainRunLoop()
            runLoop.addTimer(uiUpdateTimer, forMode: NSDefaultRunLoopMode)
    
            progressWindow.beginSheetModalForWindow(self.view.window!, completionHandler: nil)
        }
    
        func closeSheet() {
            self.view.window?.endSheet(self.progressWindow.window)
        }
    
    }