[英] SwiftUI's application(_ openFile:) never called when opening a file from Finder
我有一个使用SwiftUI构建的单窗口macOS应用程序.应用程序导出一个新的类型标识符,并将自己注册为该文档类型的编辑器.
预期行为:双击该类型的文件时,我希望应用程序启动(如果未运行),并使用文件路径调用我的AppDelegate应用程序(\uOpenFile:)方法.
实际行为:应用程序启动,但从未调用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>
App file:
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应用程序(\uOpenFile:)方法,而不是打开新窗口?