Skip to content

Instantly share code, notes, and snippets.

@ShonFrazier
Forked from anonymous/HandleURI.swift
Last active September 15, 2016 01:50
Show Gist options
  • Save ShonFrazier/6ba66510716ce27730fde75ba88df861 to your computer and use it in GitHub Desktop.
Save ShonFrazier/6ba66510716ce27730fde75ba88df861 to your computer and use it in GitHub Desktop.
Handle URIs with custom schemes on macOS
// After your application launches, register to handle Apple Events
func applicationDidFinishLaunching(_ aNotification: Notification)
{
let appleEventManager = NSAppleEventManager.shared()
appleEventManager.setEventHandler(self,
andSelector: #selector(AppDelegate.handleGetURLEvent(_:withReplyEvent:)),
forEventClass: AEEventClass(kInternetEventClass),
andEventID: AEEventID(kAEGetURL))
}
// When the Apple Event is handed to your app, get the URI from it
func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor)
{
let uriString = event.paramDescriptor(forKeyword: keyDirectObject)?.stringValue!
print("\(uriString)")
}
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>MyScheme</string>
<key>CFBundleURLSchemes</key>
<array>
<string>myscheme</string>
</array>
</dict>
</array>
import Cocoa
NSWorkspace.shared().open(URL(string: "myscheme://path/to/whatever")!)
@ShonFrazier
Copy link
Author

In your Info.plist, add the content above to the top-level dictionary

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment