SwiftUI 的应用程序(_ openFile:) 从 Finder 打开文件时从未调用



我有一个使用SwiftUI构建的单窗口macOS应用程序。应用程序导出一个新的类型标识符,并将自己注册为该文档类型的Editor。

预期行为:当双击该类型的文件时,我希望应用程序启动(如果没有运行),并为我的AppDelegate应用程序(_ openFile:)方法调用文件的路径。

实际行为:应用程序启动,但从未调用openFile。如果应用程序已经在运行,则会创建一个新的主窗口,这也是我不想要的,并且openFile也不会被调用。

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>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>Launch Tester File</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Default</string>
<key>LSItemContentTypes</key>
<array>
<string>com.mrrsoftware.ltfile</string>
</array>
</dict>
</array>
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.json</string>
</array>
<key>UTTypeDescription</key>
<string>Launch Tester File</string>
<key>UTTypeIcons</key>
<dict/>
<key>UTTypeIdentifier</key>
<string>com.mrrsoftware.ltfile</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>ltfile</string>
</array>
</dict>
</dict>
</array>
</dict>
</plist>

应用程序文件:

import SwiftUI
@main
struct LaunchTesterApp: App {
@NSApplicationDelegateAdaptor private var appDeletate : MyAppDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
.commands {
CommandGroup(replacing: .newItem, addition: { })
}
}
}
class MyAppDelegate: NSObject, NSApplicationDelegate, ObservableObject {
func applicationWillFinishLaunching(_ notification: Notification) {
print("WillFinishLaunching")
}

func applicationDidFinishLaunching(_ notification: Notification) {
print("DidFinishLaunching")
NSWindow.allowsAutomaticWindowTabbing = false
}

func application(_ sender: NSApplication, openFile filename: String) -> Bool {
print( "AppDelegate openFile: (filename)")
return true
}
}

我如何让应用程序调用我的AppDelegate application(_ openFile:)方法而不是打开一个新窗口?

使用

class AppDelegate: NSObject, NSApplicationDelegate {
func application(_ application: NSApplication, open urls: [URL]) {
print(">> (urls)")
}

在Xcode 13.4/macOS 12.4下测试

最新更新