How to capture the URL used to launch an OS X appl

2020-02-11 05:38发布

问题:

I've been trying to replicate the usual way of doing this in Objective-C in Swift for a new swift app I'm playing around with.

How to do this in Objective-C is well documented, you get the shared apple event manager and call setEventHandler method to register a function as the handler for the event class kInternetEventClass with the event id kAEGetURL.

So in swift I'm trying to do the same thing with this code added to the template AppDelegate.swift inside a brand new project:

func applicationWillFinishLaunching(aNotification: NSNotification?) {
    var appleEventManager:NSAppleEventManager = NSAppleEventManager.sharedAppleEventManager()
    appleEventManager.setEventHandler(self, andSelector: "handleGetURLEvent:withReplyEvent:", forEventClass: kInternetEventClass, andEventID: kAEGetURL)
}

func handleGetURLEvent(event: NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?) {
    println("yay");
}

As far as I can tell this is just a syntax conversion of the standard Objective-c call. But I get a type error for both the forEventClass and andEventId arguments to the setEventHandler method:

'NSNumber' is not a subtype of 'AEEventClass' for the forEventClass argument

and:

'NSNumber' is not a subtype of 'AEEventId' for the andEventID argument

I'm not sure what I'm doing wrong at this stage as both kInternetEventClass and kAEGetURL are constants defined by apple... Surely I'm not required to convert their NSNumber type to their respective required types? And if I am I can't work out how.

回答1:

As far as I can tell from the documentation the classes takes the constant and converts it to the proper type:

func applicationWillFinishLaunching(aNotification: NSNotification?) {
    var appleEventManager:NSAppleEventManager = NSAppleEventManager.sharedAppleEventManager()
    appleEventManager.setEventHandler(self, andSelector: "handleGetURLEvent:withReplyEvent:", forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}


回答2:

I found that as of Xcode 8.2 I needed to convert MagerValp's code to the following:

func applicationWillFinishLaunching(_ notification: Notification) {
    let aem = NSAppleEventManager.shared();
    aem.setEventHandler(self, andSelector: Selector(("handleGetURLEvent:withReplyEvent:")), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}

Hope this helps.