我有一個使用 SwiftUI 構建的單視窗 macOS 應用程式。應用程式匯出一個新的型別識別符號并將自己注冊為該檔案型別的編輯器。
預期行為:雙擊該型別的檔案時,我希望應用程式啟動(如果未運行),并使用檔案路徑呼叫我的 AppDelegate 應用程式(_ openFile:) 方法。
實際行為:應用程式啟動但 openFile 從未被呼叫。如果應用程式已經在運行,則會創建一個我也不想要的新主視窗,并且永遠不會再次呼叫 openFile。
資訊串列:
<?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:) 方法而不是打開新視窗?
uj5u.com熱心網友回復:
改為使用
class AppDelegate: NSObject, NSApplicationDelegate {
func application(_ application: NSApplication, open urls: [URL]) {
print(">> \(urls)")
}
使用 Xcode 13.4 / macOS 12.4 測驗
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/495248.html
下一篇:這不會又是一個Go的BUG吧?
