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.