Skip to content

Instantly share code, notes, and snippets.

@mminer
Last active October 18, 2017 04:53
Show Gist options
  • Save mminer/31acb0d2ad0c378a752ed2e99c106d26 to your computer and use it in GitHub Desktop.
Save mminer/31acb0d2ad0c378a752ed2e99c106d26 to your computer and use it in GitHub Desktop.
Registers a Cocoa application to handle a custom URL scheme (e.g. someapp://action).
import Foundation
class URLSchemeHandler {
private let urlHandler: (URL) -> Void
init(urlHandler: @escaping (URL) -> Void) {
self.urlHandler = urlHandler
NSAppleEventManager.shared().setEventHandler(
self,
andSelector: #selector(handleURLEvent(_:withReplyEvent:)),
forEventClass: AEEventClass(kInternetEventClass),
andEventID: AEEventID(kAEGetURL)
)
}
/// Handles an incoming custom URL.
@objc
private func handleURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent: NSAppleEventDescriptor) {
let keyword = AEKeyword(keyDirectObject)
guard
let urlString = event.paramDescriptor(forKeyword: keyword)?.stringValue,
let url = URL(string: urlString)
else {
print("Received invalid custom URL.")
return
}
print("Received URL from custom scheme: \(url)")
urlHandler(url)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment