当我的应用程序启动时,我想在没有用户干预的情况下自动打开保存的最后一个文档。我的计划是将上次保存的文件的位置保存到dataOfType中的user-defaults中。我还将通过在app-controller中的applicationShouldOpenUntitledFile中返回NO来阻止打开无标题文档。所以在理论上这应该是可能的,但如何?如何以编程方式打开文档?
答案 0 :(得分:5)
我从Cocoa with Love中找到了这个答案。
- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
{
// On startup, when asked to open an untitled file, open the last opened
// file instead
if (!applicationHasStarted)
{
// Get the recent documents
NSDocumentController *controller =
[NSDocumentController sharedDocumentController];
NSArray *documents = [controller recentDocumentURLs];
// If there is a recent document, try to open it.
if ([documents count] > 0)
{
NSError *error = nil;
// point to last document saved
NSInteger index = 0;
[controller
openDocumentWithContentsOfURL:[documents objectAtIndex:index]
display:YES error:&error];
// If there was no error, then prevent untitled from appearing.
if (error == nil)
{
return NO;
}
}
}
return YES;
}
答案 1 :(得分:1)
Swift 4示例:(代码进入您的应用程序代理)
func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
let documentController = NSDocumentController.shared
if let mostRecentDocument = documentController.recentDocumentURLs.first {
documentController.openDocument(withContentsOf: mostRecentDocument, display: true, completionHandler: { (document, documentWasAlreadyOpen, errorWhileOpening) in
// Handle opened document or error here
})
return false
} else {
return true
}
}