Deeplinks in macOS

363 Views Asked by At

I am trying to write an desktop app in swift, for macOS, which is going to consume my deeplink myurl://test. I was trying to create Console Application for it, however apparenntly I couldn't add Info.plist file to it. As a walkarounnd I have created very simple UI app, with following code:

//My delegate 


import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate {
    func application(_ application: NSApplication, open urls: [URL]) 
    {
        for url in urls {
            print("Handle url: ", url);
        }
    }
}
//My Info.plist file


<?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>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Viewer</string>
            <key>CFBundleURLName</key>
            <string>my.org,com.myhandler</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>mylink</string>
            </array>
        </dict>
    </array>
</dict>
</plist>

//main file


import SwiftUI

@main
struct SMBUrlHelperSecondApproachApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
    var body: some Scene {
        WindowGroup {
            Text("")
        }
    }
}

I am testing it using command open mylink://path/to/my/file I would expect an url printed, but instead, urls array is empty.

func application(_ application: NSApplication, open urls: [URL]) {
        for url in urls {

Any idea, what might be wrong here? I am pretty new in swift, so any extra advises will be appriciated.

1

There are 1 best solutions below

0
Maciek Wagner On

In the end I have used apple events handler and it worked for me.

func applicationDidFinishLaunching(_ aNotification: Notification) {
        NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(self.handleAppleEvent(event:replyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
        }
    @objc func handleAppleEvent(event: NSAppleEventDescriptor, replyEvent: NSAppleEventDescriptor) {
            guard let appleEventDescription = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject)) else {
                return
            }
            
            if let appleEventURLString = appleEventDescription.stringValue {
                guard let appleEventURL = URL(string: appleEventURL) else {
                    return
                }
                
    
                if service.service_started {
                    print(appleEventURL)
                }
    
            }