0

I am new to Swift UI and currently working on a menu bar app for MacOS. I created a AppDelegate in which there is a method which toggles the menu bar popover when the icon in the menu bar is clicked - This is all working perfectly.

Now I want to use this method from another class, so that on a certain event the menu bar app appears or disappears.

This is how I get the reference of the AppDelegate and call the method:

@NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate

appDelegate.togglePopover()

And this is the togglePopover() method inside the AppDelegate:

@objc func togglePopover() {
        
        if let button = statusItem.button {
            if popover.isShown {
                self.popover.performClose(nil)
            } else {
                popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
            }
        }
        
    }

The method is executed but I get the following error:

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

I have tried to get the reference of the AppDelegate in various ways which all did not work. For example:

let appDelegate = NSApplication.shared.delegate as? AppDelegate or let appDelegate = UIApplication.shared.delegate as! AppDelegate

Does anyone have a clue how to solve this problem? - Thanks in advance.

  • 1
    This is a very unusual code for a popover. And very unusual to set its state from AppDelegate (I mean if you have many forms and many popovers, are you going to put them all in AppDelegate???). Instead move this code to the view which displays a popover, and also follow some tutorial which explains how to create a popover. For example: https://www.hackingwithswift.com/quick-start/swiftui/how-to-show-a-popover-view – timbre timbre Feb 25 '23 at 20:24

0 Answers0