gpt4 book ai didi

swift - NSCocoaErrorDomain Code=256 无法打开 “md” 格式的文件

转载 作者:行者123 更新时间:2023-11-28 13:50:18 24 4
gpt4 key购买 nike

我正在开发一个用于编辑文件的 macOS 应用程序,但是在尝试使用 NSDocumentController.shared.makeDocument 创建一个新的 NSDocument 实例时遇到了一个相当烦人的错误来自文件 URL。

下面是我如何调用 makeDocument 的简单示例。文件 test.md 存在于磁盘上。

let url = URL(fileURLWithPath: "/Users/me/Desktop/test.md"

do {
let newDocument = try NSDocumentController.shared.makeDocument(withContentsOf: url, ofType: url.pathExtension)
print("Created \(newDocument)")
} catch {
print("Error: \(error)")
}

问题在于此 try 调用失败并到达 catch block 。我得到的错误是:

Error: Error Domain=NSCocoaErrorDomain Code=256 "“test.md” could not be handled because MyApp cannot open files in the “md” format." UserInfo={NSLocalizedDescription=“test.md” could not be handled because MyApp cannot open files in the “md” format., NSLocalizedFailureReason= MyApp cannot open files in the “md” format.}

我相信我已经为 Markdown 文件正确设置了应用的文档类型,如下所示:

info

我已经尝试清理构建、删除派生数据并为 Markdown 文件添加“导入的 UTI”类型,但似乎没有任何效果。

奇怪的是,通过文件 > 打开,我能够打开 .md 文件,只是不能通过 makeDocument 以编程方式打开。

最佳答案

makeDocument(withContentsOf:ofType:) 需要一个类型作为第二个参数,而不是扩展。查看 typeForContents(of url: URL) 了解如何从 URL 派生类型。

参见https://developer.apple.com/library/archive/documentation/DataManagement/Conceptual/DocBasedAppProgrammingGuideForOSX/AdvancedTopics/AdvancedTopics.html中的图6-3

正如 Marek H 在他的回答中指出的那样,在 info.plist 中应该有一个用于文档类型的 UTI(标识符)。

关于swift - NSCocoaErrorDomain Code=256 无法打开 “md” 格式的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54729686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com