Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.


A Q&D error display for the key window

During development it is convenient to have a simple error display routine that shows whatever text you throw into it in the frontmost (key) window.

There is an easy way to accomplish this, just add a global function (for example in the AppDelegate file):

func showErrorInKeyWindow(_ message: String) {
    if let window = NSApp.keyWindow {
        DispatchQueue.main.async {
            let alert = NSAlert()
            alert.messageText = "Error"
            alert.informativeText = message
            alert.addButton(withTitle: "Dismiss")
            alert.beginSheetModal(for: window, completionHandler: nil)
    else {
        log.atLevelError(id: -1, source: #file.source(#function, #line), message: "Could not send error message '\(message)' to key window")


Of course you can replace the error logging with a simple "print" statement as long as you are working in Xcode. Otherwise you could use the SwifterLog logging project (free from github, see link at right side)

Now anywhere in your code where you need to flash an error, just call "showErrorInKeyWindow(message)"

(But beware for repeating error's ;-))

Note: Do not use this in shipping code. Yes, you could, but you really should have a something better in place.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment