如何使用 Mac-Catalyst 添加最近的文件

shu*_*una 4 swift mac-catalyst

在默认的“文件”菜单中,它有“打开最近的>”菜单项,并且它是自动添加的。目前,如果用户从 Finder 打开关联文件,则会自动添加最近的项目(在 Big Sur 上)。但是如果用户使用 UIDocumentPickerViewController 从我的应用程序打开,它不会添加最近的菜单项。

在此输入图像描述

我想在“打开最近的>”下添加此菜单项并从我的代码中清除项目。有帮助文档或者示例代码吗?谢谢。

Voo*_*oot 8

在 macOS Big Sur 中,UIDocument.open()自动将打开的文件添加到“打开最近使用的文件”菜单中。但是,菜单项没有文件图标(AppKit 中有文件图标!)。\n您可以查看 Apple 的示例构建基于文档浏览器的应用程序UIDocumentBrowserViewController,以获取使用和的示例UIDocument

\n

获取真实的东西要复杂得多,并且涉及到调用 Objective-C 方法。我知道有两种方法可以使用 UIKit+AppKit 手动填充“打开最近的”菜单\xe2\x80\x94,或使用私有 AppKit API“自动”填充。后者应该也可以在 Mac Catalyst 的早期版本(Big Sur 之前)中工作,但在 UIKit 中存在更多错误。

\n

由于您无法直接在 Mac Catalyst 应用程序中使用 AppKit,因此有两种选择:

\n
    \n
  1. 创建一个使用 Swift 或 Objective-C 桥接到 AppKit 的应用程序包,并从应用程序加载该包。
  2. \n
  3. 使用字符串从基于 UIKit 的应用程序调用 AppKit API。我正在使用Dynamic包。
  4. \n
\n

手动填充“打开最近使用的内容”菜单

\n

下面显示的示例是从 Mac Catalyst 调用 AppKit。

\n
class AppDelegate: UIResponder, UIApplicationDelegate {\n    override func buildMenu(with builder: UIMenuBuilder) {\n        guard builder.system == .main else { return }\n\n        var recentFiles: [UICommand] = []\n        if let recentFileURLs = ObjC.NSDocumentController.sharedDocumentController.recentDocumentURLs.asArray {\n            for i in 0..<(recentFileURLs.count) {\n                guard let recentURL = recentFileURLs.object(at: i) as? NSURL else { continue }\n                guard let nsImage = ObjC.NSWorkspace.sharedWorkspace.iconForFile(recentURL.path).asObject else { continue }\n                guard let imageData = ObjC(nsImage).TIFFRepresentation.asObject as? Data else { continue }\n                let image = UIImage(data: imageData)?.resized(fittingHeight: 16)\n                guard let basename = recentURL.lastPathComponent else { continue }\n                let item = UICommand(title: basename,\n                                     image: image,\n                                     action: #selector(openDocument(_:)),\n                                     propertyList: recentURL.absoluteString)\n                recentFiles.append(item)\n            }\n        }\n\n        let clearRecents = UICommand(title: "Clear Menu", action: #selector(clearRecents(_:)))\n        if recentFiles.isEmpty {\n            clearRecents.attributes = [.disabled]\n        }\n        let clearRecentsMenu = UIMenu(title: "", options: .displayInline, children: [clearRecents])\n\n        let recentMenu = UIMenu(title: "Open Recent",\n                                identifier: nil,\n                                options: [],\n                                children: recentFiles + [clearRecentsMenu])\n        builder.remove(menu: .openRecent)\n\n        let open = UIKeyCommand(title: "Open...",\n                                action: #selector(openDocument(_:)),\n                                input: "O",\n                                modifierFlags: .command)\n        let openMenu = UIMenu(title: "",\n                              identifier: nil,\n                              options: .displayInline,\n                              children: [open, recentMenu])\n        builder.insertSibling(openMenu, afterMenu: .newScene)\n    }\n\n    @objc func openDocument(_ sender: Any) {\n        guard let command = sender as? UICommand else { return }\n        guard let urlString = command.propertyList as? String else { return }\n        guard let url = URL(string: urlString) else { return }\n        NSLog("Open document \\(url)")\n    }\n\n    @objc func clearRecents(_ sender: Any) {\n        ObjC.NSDocumentController.sharedDocumentController.clearRecentDocuments(self)\n        UIMenuSystem.main.setNeedsRebuild()\n    }\n\n
Run Code Online (Sandbox Code Playgroud)\n

菜单不会自动刷新。您必须通过调用 来触发重建UIMenuSystem.main.setNeedsRebuild()。每当您打开文档(例如在提供给 的块中UIDocument.open())或保存文档时,您都必须执行此操作。下面是一个例子:

\n
class MyViewController: UIViewController {\n    var document: UIDocument? // set by the parent view controller\n    override func viewWillAppear(_ animated: Bool) {\n        super.viewWillAppear(animated)\n\n        // Access the document\n        document?.open(completionHandler: { (success) in\n            if success {\n                // Display the document\n            } else {\n                // Report error\n            }\n\n            // 500 ms is probably too long\n            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {\n                UIMenuSystem.main.setNeedsRebuild()\n            }\n        })\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

自动填充菜单 (AppKit)

\n

以下示例使用:

\n
    \n
  1. NSMenu\ 的私有 API_setMenuName:用于设置菜单名称以使其本地化,以及
  2. \n
  3. NSDocumentController\的_installOpenRecentMenus“打开最近的”菜单。
  4. \n
\n
- (void)setupRecentMenu {\n    NSMenuItem *clearMenuItem = [self _findMenuItemWithName:@"Open Recent" in:NSApp.mainMenu.itemArray];\n    if (!clearMenuItem) {\n        NSLog(@"Warning: \'Open Recent\' menu not found");\n        return;\n    }\n    NSMenu *openRecentMenu = [[NSMenu alloc] initWithTitle:@"Open Recent"];\n    [openRecentMenu performSelector:NSSelectorFromString(@"_setMenuName:") withObject:@"NSRecentDocumentsMenu"];\n    clearMenuItem.submenu = openRecentMenu;\n\n    [NSDocumentController.sharedDocumentController valueForKey:@"_installOpenRecentMenus"];\n}\n\n- (NSMenuItem * _Nullable)_findMenuItemWithName:(NSString * _Nonnull)name in:(NSArray<NSMenuItem *> * _Nonnull)array {\n    for (NSMenuItem *item in array) {\n        if ([item.title isEqualToString:name]) {\n            return item;\n        }\n        if (item.hasSubmenu) {\n            NSMenuItem *subitem = [self _findMenuItemWithName:name in:item.submenu.itemArray];\n            if (subitem) {\n                return subitem;\n            }\n        }\n    }\n    return nil;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

在你的buildMenu(with:)

\n
class AppDelegate: UIResponder, UIApplicationDelegate {\n    override func buildMenu(with builder: UIMenuBuilder) {\n        guard builder.system == .main else { return }\n\n        let open = UIKeyCommand(title: "Open...",\n                                action: #selector(openDocument(_:)),\n                                input: "O",\n                                modifierFlags: .command)\n        let recentMenu = UIMenu(title: "Open Recent",\n                                identifier: nil,\n                                options: [],\n                                children: [])\n        let openMenu = UIMenu(title: "",\n                              identifier: nil,\n                              options: .displayInline,\n                              children: [open, recentMenu])\n        builder.remove(menu: .openRecent)\n        builder.insertSibling(openMenu, afterMenu: .newScene)\n\n        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in\n            self?.myObjcBridge?.setupRecentMenu()\n        }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

但是,我发现这种方法存在一些问题。图标似乎已关闭(它们更大),并且“清除菜单”命令在第一次使用后并未禁用。重建菜单可以解决该问题。

\n

2020 年 12 月 30 日更新

\n

macCatalyst 14 (Big Sur) 确实安装了“打开最近使用的”菜单,但该菜单没有图标。

\n

使用 Dynamic 包的速度明显慢。我按照 Peter Steinberg 的演讲在 Objective-C 中实现了相同的逻辑。虽然这有效,但我注意到图标太大,而且我找不到解决该问题的方法。

\n

此外,使用 AppKit 的私有 API,“打开最近的”字符串不会自动本地化(但“清除菜单”会自动本地化!)。

\n

我目前的做法是:

\n
    \n
  1. 使用应用程序包(在 Objective-C 中),\na) 用于NSDocumentController查询最近的文件。\nb) 用于NSWorkspace获取文件的图标。
  2. \n
  3. buildMenu方法调用包,获取文件/图标并手动创建菜单项。
  4. \n
  5. 应用程序包加载NSImageNameMenuOnStateTemplate系统图像并将此大小提供给 macCatalyst 应用程序,以便它可以重新缩放图标。
  6. \n
\n

请注意,我还没有实现安全书签的逻辑(对此不熟悉,需要进一步研究)。彼得谈到了这一点。

\n

显然,我需要自己提供字符串的翻译。但没关系。

\n

这是应用程序包中的相关代码:

\n
\n@interface RecentFile: NSObject<RecentFile>\n- (instancetype)initWithURL: (NSURL * _Nonnull)url icon:(NSImage *)image;\n@end\n\n@implementation AppKitBridge\n@synthesize recentFiles;\n@synthesize menuIconSize;\n@end\n\n- (instancetype)init {\n    // ...\n    NSImage *templateImage = [NSImage     imageNamed:NSImageNameMenuOnStateTemplate];\n    self->menuIconSize = templateImage.size;\n}\n\n- (NSArray<NSObject<RecentFile> *> *)recentFiles {\n    NSArray<NSURL *> *recents = [[NSDocumentController sharedDocumentController] recentDocumentURLs];\n    NSMutableArray<SGRecentFile *> *result = [[NSMutableArray alloc] init];\n    for (NSURL *url in recents) {\n        if (!url.isFileURL) {\n            NSLog(@"Warning: url \'%@\' is not a file URL", url);\n            continue;\n        }\n        NSImage *icon = [[NSWorkspace sharedWorkspace] iconForFile:[url path]];\n        RecentFile *f = [[RecentFile alloc] initWithURL:url icon:icon];\n        [result addObject:f];\n    }\n    return result;\n}\n\n- (void)clearRecentFiles {\n    [NSDocumentController.sharedDocumentController clearRecentDocuments:self];\n}\n
Run Code Online (Sandbox Code Playgroud)\n

UIMenu然后从 macCatalyst 代码填充:

\n
@available(macCatalyst 13.0, *)\nfunc createRecentsMenuCatalyst(openDocumentAction: Selector, clearRecentsAction: Selector) -> UIMenuElement {\n    var commands: [UICommand] = []\n    if let recentFiles = appKitBridge?.recentFiles {\n        for rf in recentFiles {\n            var image: UIImage? = nil\n            if let cgImage = rf.image {\n                image = UIImage(cgImage: cgImage).scaled(toHeight: menuIconSize.height)\n            }\n            let cmd = UICommand(title: rf.url.lastPathComponent,\n                                image: image,\n                                action: openDocumentAction,\n                                propertyList: rf.url.absoluteString)\n            commands.append(cmd)\n        }\n    }\n    let clearRecents = UICommand(title: "Clear Menu", action: clearRecentsAction)\n    if commands.isEmpty {\n        clearRecents.attributes = [.disabled]\n    }\n    let clearRecentsMenu = UIMenu(title: "", options: .displayInline, children: [clearRecents])\n\n    let menu = UIMenu(title: "Open Recent",\n                      identifier: UIMenu.Identifier("open-recent"),\n                      options: [],\n                      children: commands + [clearRecentsMenu])\n    return menu\n}\n
Run Code Online (Sandbox Code Playgroud)\n

来源

\n\n