如何确定文件的文件类型(文档类型/UTI)

How do I figure out the file type (document type / UTI) of a file

我正在开发文档应用程序。我的文档实际上是一个可以容纳其他任意文档的包。加载我的文档后,我可以使用 NSFileWrapper API 获取所有这些文件的句柄。我想知道那些 NSFileWrapper 对象代表什么类型的文件,所以我知道如何在我的应用程序中显示它。它是文本文件、图像还是某些二进制文件?

有没有办法获取 NSFileWrapper 的 UTI?我确实在来自 AppKit 的 NSFileWrapper 上找到了 'icon' 属性。所以他们必须有某种方式知道文件是什么才能查找它的图标。

您可以向 NSWorkspace 询问任何文件的 UTI:

import Cocoa

let documents = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
  .UserDomainMask, true)[0] as! String

let documentPath = documents.stringByAppendingPathComponent("test.pages")
  // test.pages will need to exist on the filesystem

NSWorkspace.sharedWorkspace().typeOfFile(documentPath, error: nil)
  // com.apple.iwork.pages.sffpages

我不确定它的可靠性如何,或者如果有多个应用程序能够打开同一个文件会发生什么情况。

文档鼓励检查 NSError 但没有说明可能会发生什么错误。