【问题标题】:Execute code before state restoration happens (macOs)在状态恢复发生之前执行代码(macOs)
【发布时间】:2019-03-26 14:37:39
【问题描述】:

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

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

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

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

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

谢谢

【问题讨论】:

    标签: swift xcode nsdocument nsapplication state-restoration


    【解决方案1】:

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

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

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

    在我的 Document 类中,我覆盖了 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];
            }
        }
    }
    

    所以打开的第一个文档窗口会显示模态对话框并在用户不接受时退出应用程序。

    您可以add a NSTextField to a NSAlert 索取许可证密钥。

    【讨论】:

      猜你喜欢
      • 2012-12-04
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多