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

问题描述 投票:0回答:2

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

enter image description here

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

swift mac-catalyst
2个回答
8
投票

在 macOS Big Sur 中,

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

获取真实的东西要复杂一些,并且涉及到调用 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,“打开最近的”字符串不会自动本地化(但“清除菜单”会自动本地化!)。

我目前的做法是:

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

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

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

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


@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
}

来源


0
投票

我没有基于 NSDocument 的应用程序。从 Ventura 和 Sonoma 开始,当我打开文件时,只需在基于 AppKit 的插件中调用 NSDocumentController.shared.noteNewRecentDocumentURL(url) 即可显示“打开最近的文档”菜单并发挥作用,并在 Catalyst 代码中通过实现当从菜单中选择最近的 URL 时,场景委托方法 scene(_ scene: UIScene, openURLContexts URLContexts: Set) 。

菜单自动出现,清晰工作等等。我不需要编写其他代码。但我没有看到文件旁边的图标。不知道为什么会这样。

© www.soinside.com 2019 - 2024. All rights reserved.