How to handle custom URL scheme while macOS Command Line Tool is running
Asked Answered
S

0

7

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?

Swum answered 8/6, 2018 at 11:7 Comment(3)
Did you ever find a solution to this problem?Gussi
No, sorry 🙂 I wish I could.Swum
I'd really like to do oauth from CLI much like Google does with their firebase CLI tools.. Opening the webpage is easy enough but if I can't intercept the callback I guess I'm out of luck :/ Adding a bounty.Gussi

© 2022 - 2024 — McMap. All rights reserved.