如何在 macOS 命令行工具运行时处理自定义 URL 方案

Vad*_*dim 7 url executable command-line-interface info.plist swift

我正在构建一个命令行工具,它应该在运行时监听自定义 URL 方案:

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)
Run Code Online (Sandbox Code Playgroud)

代码签名包括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>
Run Code Online (Sandbox Code Playgroud)

即使LSSetDefaultHandlerForURLScheme成功返回,macOS 也无法打开 URL,myscheme://test例如通过 Safari 或通过终端。

我是否遗漏了任何内容,或者通过 CLI 处理自定义 URL 是正式不可能的吗?