Registering URL handlers in MacOS X Cocoa Apps

As a personal hobby project, I’m playing with writing MacOS X applications, which is something I have always wanted to do and am now enjoying now I’ve got over the first frustrating few hours (the breakthrough was realising it was in fact quite like Smalltalk, which I loved).

I should preface this with the fact that I really have no idea what I am doing, which makes it kind of fun for me although I might be making some basic mistakes! Anyway, I hope this helps someone…

I want my App to respond to a URL scheme, so I followed the example here on CocoaDev. Which worked first time when I had the application running in the debugger. You put your URL schemes in the .plist file and then I had done this in my applicationDidFinishLaunching: method (as I didn’t have an init() method in the class already – maybe I should have created one but I wondered if that had been deprecated):


[[NSAppleEventManager sharedAppleEventManager] setEventHandler:self
andSelector:@selector(getUrl:withReplyEvent:)
forEventClass:kInternetEventClass
andEventID:kAEGetURL];

My problem was when the application wasn’t running, it would launch in response to the URL click, but it wouldn’t process the URL – it was being thrown away.

The trick was to put it in the applicationWillFinishLaunching: method, which now looks like this:

// This is called just before it will finish launching
- (void)applicationWillFinishLaunching:(NSNotification *)aNotification {
// Register ourselves as a URL handler for this URL
[[NSAppleEventManager sharedAppleEventManager] setEventHandler:self
andSelector:@selector(getUrl:withReplyEvent:)
forEventClass:kInternetEventClass
andEventID:kAEGetURL];
}

(note in the code examples above, I’ve split the lines to make them more readable)

Comments 1

Leave a Reply

Your email address will not be published. Required fields are marked *