macoscocoaurlurl-schemelaunch-services

When an OS X app is launched by a registered URL scheme, how do you access the full URL?


I'm working on an Cocoa app which is launched/activated using URLs with a custom scheme which is registered in the Info.plist file like so:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string>Open myscheme:// URLs</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>myscheme</string>
        </array>
    </dict>
</array>

My question is, once the app is launched or activated, how do I tell what the URL was that launched the app? On iOS, this is easy with the -application:openURL:sourceApplication:annotation: method on the UIApplicationDelegate since it is passed an NSURL instance.

I want to be able to pass in data into my app with URLs like myscheme://do/something/awesome


Solution

  • In your app delegate's -applicationWillFinishLaunching:, do:

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

    And handleAppleEvent:withReplyEvent: should look something like:

    - (void)handleAppleEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent {
        NSString *urlString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
        // do something with the URL string
    }