Receive file open event without NSApplication
I need receive a launch-time file open event in my app (I.e. I needed to know when it was launched by double-clicking an associated file). However I also need to avoid using NSApplication for... complex reasons.
So I'm trying to register for apple events and briefly run a run loop instead but I'm not having much luck. Is it at all possible to receive apple events without NSApplication?
import AppKit
import os
@main
class Runner: NSObject {
static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "debug")
static func main() throws {
logger.log("main")
let runner = Runner()
NSAppleEventManager.shared().setEventHandler(
runner,
andSelector: #selector(handleOpenEvent(_:withReplyEvent:)),
forEventClass: AEEventClass(kCoreEventClass),
andEventID: AEEventID(kAEOpenDocuments)
)
RunLoop.current.run(until: Date().addingTimeInterval(3))
try runner.run()
}
@objc func handleOpenEvent(_ event: NSAppleEventDescriptor, withReplyEvent reply: NSAppleEventDescriptor) {
Self.logger.debug("handleOpenEvent")
let list = event.paramDescriptor(forKeyword: keyDirectObject)
for i in 1...(list?.numberOfItems ?? 0) {
if let fileDesc = list?.atIndex(i), let url = fileDesc.fileURLValue {
Self.logger.log("aeurl: \(url)")
}
}
}
func run() throws {
Self.logger.log("run")
}
}