首页 > 解决方案 > 在状态恢复发生之前执行代码(macOs)

问题描述

我正在为 Swift 4 中的 Mac 编写一个基于文档的应用程序,根据我的客户需要,如果用户将提供其许可证密钥,它必须显示一个许可窗口。

我在方法中显示了这个窗口applicationWillFinishLaunching()。当此窗口处于活动状态时,状态恢复方法在后台运行并加载以前的 nsdocument,或者如果没有以前的则创建空的。我想避免这种情况,我希望能够选择何时恢复并表现得像基于文档的应用程序启动。

我试图在 appDelegate 方法中拦截应用程序的启动,applicationShouldOpenUntitledFile(_ sender: NSApplication)但没有成功。然后我在这里读到,如果应用程序状态恢复处于活动状态,则不会调用此方法。为了确认这一点,我停用了恢复,然后没有按预期加载/创建最后一个文档或空文档。伟大的!

但后来,我失去了很好的恢复功能。

我想知道是否有更好的方法来做到这一点:在基于文档的应用程序中显示许可屏幕,停止恢复方法,并在应用程序获得许可后手动调用它们。

谢谢

标签: swiftxcodensdocumentnsapplicationstate-restoration

解决方案


这是Objective C,但我这样做是为了显示一个对话框,在该对话框中用户必须接受一些许可条件:

在我的 AppDelegate 中,我得到了一个licenseDialogOpen在应用启动时设置为 false 的属性。

@synthesize licenseDialogOpen;

- (instancetype)init {
    self = [super init];
    if (self) {
        self.licenseDialogOpen = FALSE;
    }
    return self;
}

在我的文档类中,我覆盖了windowControllerDidLoadNib

- (void)windowControllerDidLoadNib:(NSWindowController *)windowController {
    [super windowControllerDidLoadNib:windowController];

    AppDelegate *appDelegate = [NSApp delegate];

    if (!appDelegate.licenseDialogOpen) {
        NSAlert *alert = [[NSAlert alloc] init];
        [alert setMessageText:NSLocalizedString(@"License conditions and disclaimer:", nil)];
        [alert setInformativeText:NSLocalizedString(@"License bla bla disclaimer bla bla bla", nil)];
        [alert setAlertStyle:NSAlertStyleWarning];
        [alert addButtonWithTitle:NSLocalizedString(@"Accept", nil)];
        [alert addButtonWithTitle:NSLocalizedString(@"Quit", nil)];

        [alert.window makeFirstResponder:[[alert buttons] firstObject]];

        appDelegate.licenseDialogOpen = TRUE;
        NSModalResponse answer = [alert runModal];
        if (answer != NSAlertFirstButtonReturn) {
            for (NSWindow *window in [NSApplication sharedApplication].windows) {
                [window close];
            }
            [NSApp terminate:self];
        }
    }
}

因此,打开的第一个文档窗口显示模式对话框并在用户不接受时退出应用程序。

您可以将 NSTextField 添加到 NSAlert以请求许可证密钥。


推荐阅读