2

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.

D.C.
  • 15,340
  • 19
  • 71
  • 102

1 Answers1

1

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.

Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110
  • Thanks, this looks like a good solution. Since I'm working with NSFileWrappers I don't *think* I have the full path to use with this API. So the UTI functions in the comment above seem more suitable to my task. – D.C. Jun 30 '15 at 02:39
  • @darren I'm pretty sure it is the _only_ solution, so you're going to have to find a way to make it work. If you've got an NSDocument you might be able to use that to determine the URL/path to the file wrapper through that. Alternatively you could create a file or folder in /tmp with the same name as the file wrapper and then ask NSWorkspace what type it is. – Abhi Beckert Jun 30 '15 at 03:54