swift - 在状态恢复发生之前执行代码(macOs)
问题描述
我正在为 Swift 4 中的 Mac 编写一个基于文档的应用程序,根据我的客户需要,如果用户将提供其许可证密钥,它必须显示一个许可窗口。
我在方法中显示了这个窗口applicationWillFinishLaunching()
。当此窗口处于活动状态时,状态恢复方法在后台运行并加载以前的 nsdocument,或者如果没有以前的则创建空的。我想避免这种情况,我希望能够选择何时恢复并表现得像基于文档的应用程序启动。
我试图在 appDelegate 方法中拦截应用程序的启动,applicationShouldOpenUntitledFile(_ sender: NSApplication)
但没有成功。然后我在这里读到,如果应用程序状态恢复处于活动状态,则不会调用此方法。为了确认这一点,我停用了恢复,然后没有按预期加载/创建最后一个文档或空文档。伟大的!
但后来,我失去了很好的恢复功能。
我想知道是否有更好的方法来做到这一点:在基于文档的应用程序中显示许可屏幕,停止恢复方法,并在应用程序获得许可后手动调用它们。
谢谢
解决方案
这是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以请求许可证密钥。
推荐阅读
- powerbi - 电源 BI。添加具有先前日期指标的列
- bash - powerline 忽略空壳命令
- node.js - 获取时更新数据的最佳方式
- javascript - 从组件内的表单中删除值
- php - 我的管理员在 php 中的相同 sql 查询在 laravel 中给了我不同的结果
- ruby-on-rails - Rails 5 为什么我总是在初始化方法中获得默认日期
- swagger - 我可以根据 openapi 3.0 规范将占位符或对枚举列表的引用添加到架构描述中吗?
- c# - 如何将速度值从 0,002543535 更改为 0
- angular - 对象可能为 null 或未定义
- python - 如何为 LSTM 模型创建函数以返回历史、损失和模型