swift - 在状态恢复发生之前执行代码 (macO)

标签 swift xcode nsdocument nsapplication state-restoration

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

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

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

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

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

谢谢

最佳答案

这是 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以索取许可证 key 。

关于swift - 在状态恢复发生之前执行代码 (macO),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52930716/

相关文章:

swift - 加载启动 URL 失败,错误为 : Error Domain=TVMLKitErrorDomain Code=3 "(null)"

ios - 如何设置连接到我的 UIWebView 的 UISearchBar 以便能够使用 swift 使用单词而不是 url 在 google 上进行搜索

ios - 使用 UIButton 打开我的另一个应用程序

iphone - 从 nsdictionary 分配给 nsarray 的不兼容指针类型

xcode - 在 Xcode 上创建新的基于文档的 Cocoa 应用程序的奇怪事情

objective-c - 清理App全局资源的最佳位置?

ios - 将 Assets 放入声音缓冲区

swift - 单元测试单元格为零

ios - 应用程序可以在模拟器上完美运行,但不能在物理设备上运行[在 iOS 13.3.1 上]

macos - 删除 'Show/Hide tab bar' 菜单项