I’m building a Command Line Tool which should listen to the custom URL scheme while running:
import AppKit
import CoreServices
let RunLoop = CFRunLoopGetCurrent()
class EventHandler: NSObject {
@objc(handleAppleEvent:withReplyEvent:)
func handleURLEvent(_ e: NSAppleEventDescriptor,
_ reply: NSAppleEventDescriptor) {
guard
let descriptor = e.paramDescriptor(forKeyword: .init(keyDirectObject)),
let stringValue = descriptor.stringValue,
let components = URLComponents(string: stringValue) else {
exit(EXIT_FAILURE)
}
print(components)
CFRunLoopStop(RunLoop)
}
}
let status = LSSetDefaultHandlerForURLScheme(
"myscheme" as CFString, "com.test.myscheme" as CFString)
guard status == 0 else {
print(status)
exit(EXIT_FAILURE)
}
let handler = EventHandler()
let manager = NSAppleEventManager.shared()
manager.setEventHandler(handler, andSelector: #selector(EventHandler.handleURLEvent(_:_:)),
forEventClass: .init(kInternetEventClass), andEventID: .init(kAEGetURL))
CFRunLoopRun()
exit(EXIT_SUCCESS)
The code signature includes Info.plist
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>com.test.myscheme</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>CFBundleURLName</key>
<string>com.test.myscheme.url</string>
<key>CFBundleURLSchemes</key>
<array>
<string>myscheme</string>
</array>
</dict>
</array>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
Even though LSSetDefaultHandlerForURLScheme
returns successfully, macOS cannot open the URL like myscheme://test
e.g. via Safari or via Terminal.
Do I miss anything or is it officially impossible to handle custom URLs via CLI?