Receive file open event without NSApplication

23 hours ago 3
ARTICLE AD BOX

When the user double-clicks a file, the system launches your process and sends an event to the application (kAEOpenDocuments), that event is delivered through the application's event pipeline. The system expects a normal app that has registered with the Window Server (via NSApplication. It doesn't post the event to an arbitrary run loop; you're only running RunLoop.current.run(until:...) and never creating NSApplication. So your process never registered as "the app" that should receive that event, and the open-documents event either never gets sent to you or never gets dispatched to your handler.

So, receiving open documents at launch is tied to being a real app (NSApplication), you can't fully replace that with just NSAppleEventManager + a plain run loop.

If "avoid" NSApplication really means "avoid a normal app event/loop" windows, you can still use a minimal app instance so the system delivers the event.

You can call let _ = NSApplication.shared (and, if needed, NSApplication.shared.setActivationPolicy(.accessory) so you don't get a dock icon/menubar if you want. Then you can register your handler with NSAppleEventManager.shared().setEventHandler(...). And then you can run the run loop for a short time (Or until you've sent the event).

You could either RunLoop.current.run(until: Date().addingTimeInterval(3)) as you do now, or you can run until you've handled the event (for example, set a flag in handleOpenEvent and run(until:) a deadline or run in a loop until he flag is set).

After that you can do your "non-app" work in run() (or exit and do it elsewhere), so you do use NSApplication for bootstrap and event delivery, but you don't have to run the full NSApp.run() forever.

Read Entire Article