D.C.
D.C.

Reputation: 15588

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

I am working on a document app. My document is actually a package that can hold other arbitrary documents. When my document is loaded I can get a handle to all of these files with the NSFileWrapper API. I want to know what kind of file those NSFileWrapper objects represent so I know how to show it in my app. Is it a text file, or an image, or some binary file?

Is there a way to get the UTI of an NSFileWrapper? I did find an 'icon' property on NSFileWrapper coming from AppKit. So they must have some way of knowing what the file is to be able to look up its icon.

Upvotes: 2

Views: 726

Answers (1)

Abhi Beckert
Abhi Beckert

Reputation: 33349

You can ask NSWorkspace for the UTI of any file:

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

I'm not sure how reliable it is, or what will happen if there are multiple apps capable of opening the same file.

The documentation encourages checking NSError but doesn't say what errors could occur.

Upvotes: 1

Related Questions