【问题标题】:How to add recent files with Mac-Catalyst如何使用 Mac-Catalyst 添加最近的文件
【发布时间】:2020-11-21 04:49:33
【问题描述】:

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

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

【问题讨论】:

    标签: swift mac-catalyst


    【解决方案1】:

    在 macOS Big Sur 中,UIDocument.open() 会自动将打开的文件添加到“打开最近”菜单。但是,菜单项没有文件图标(它们在 AppKit 中有!)。 您可以查看 Apple 的示例 Building a Document Browser-Based App,了解使用 UIDocumentBrowserViewControllerUIDocument 的示例。

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

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

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

    手动填充“打开最近”菜单

    从 Mac Catalyst 调用 AppKit 的示例如下所示。

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

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

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

    自动填充菜单 (AppKit)

    以下示例使用:

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

    在您的 buildMenu(with:) 方法中调用它:

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

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

    2020 年 12 月 30 日更新

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

    使用 Dynamic 包的速度非常慢。根据 Peter Steinberg 的演讲,我在 Objective-C 中实现了相同的逻辑。虽然这可行,但我注意到图标太大了,我找不到解决这个问题的方法。

    此外,使用 AppKit 的私有 API,“Open Recent”字符串不会自动本地化(但“Clear Menu”会!)。

    我目前的做法是:

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

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

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

    以下是 app bundle 中的相关代码:

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

    然后从 macCatalyst 代码中填充 UIMenu

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

    来源

    【讨论】:

    • 您的评论非常有帮助。我想从 UIKit 的 UIDocument 示例中尝试。谢谢!
    猜你喜欢
    • 2019-07-12
    • 1970-01-01
    • 2021-02-28
    • 2010-09-25
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    相关资源
    最近更新 更多