Last active
October 18, 2017 04:53
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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