Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture the URL used to launch an OS X application via URLScheme in Swift?

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.

like image 540
Mike Driver Avatar asked Jun 06 '14 10:06

Mike Driver


Video Answer


2 Answers

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))
}
like image 125
MagerValp Avatar answered Sep 30 '22 20:09

MagerValp


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.

like image 31
Thomas Cherry Avatar answered Sep 30 '22 21:09

Thomas Cherry