macOS 中的深层链接

问题描述 投票:0回答:1

我正在尝试用 Swift 为 macOS 编写一个桌面应用程序,这将消耗我的深层链接 myurl://test。 我试图为其创建控制台应用程序,但显然我无法向其中添加 Info.plist 文件。作为一个演练,我创建了非常简单的 UI 应用程序,代码如下:

//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("")
        }
    }
}

我正在使用命令测试它

open mylink://path/to/my/file
我希望打印一个 url,但 urls 数组是空的。

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

你知道,这里可能出了什么问题吗? 我对 swift 还很陌生,所以任何额外的建议都会受到欢迎。

swift macos deep-linking custom-url
1个回答
0
投票

最后我使用了苹果事件处理程序,它对我有用。

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)
                }
    
            }
© www.soinside.com 2019 - 2024. All rights reserved.