3

I have a document path as an NSString. How do I get its UTI as an NSString? I currently use LSCopyItemAttribute but that requires an FSRef and all the functions for making an FSRef seems to be deprecated.

(Note: This is for Mac OS 10.8+.)

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Mike T
  • 1,163
  • 1
  • 11
  • 27

2 Answers2

4

You will be able to get it using mobile core services framework. Refer the code below

NSString *path; // contains the file path

// Get the UTI from the file's extension:

CFStringRef pathExtension = (__bridge_retained CFStringRef)[path pathExtension];
CFStringRef type = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, NULL);
CFRelease(pathExtension);

The code snippet is taken from here.

Community
  • 1
  • 1
Vignesh
  • 10,205
  • 2
  • 35
  • 73
  • Thanks Vignesh - that looks like it should work - I will try it this afternoon and check your answer. I should have mentioned this is for Mac OS but the same function is in CoreServices Mac OS. If a file has no extension is it possible to get its UTI? – Mike T Aug 26 '14 at 06:55
  • This should work with Mac OS as well. I haven't tried though. This is merely mapping UTI's for path extension. Without extension some sort of file content look up would be needed. I don't know how to do it. I will look for it , if I find something useful I will update the post. – Vignesh Aug 26 '14 at 07:07
  • 3
    Hi Vignesh - I found this: `[inUrl getResourceValue:&uti forKey:NSURLTypeIdentifierKey error:&error];` which lets me get the UTI without using core foundation. Seems to be equivalent, no? – Mike T Aug 27 '14 at 09:49
  • @MikeT, Yes. It definitely seems equivalent. More appropriate perhaps. – Vignesh Aug 27 '14 at 10:38
2

Use can use url.resourceValues(forKeys: (as mentioned in the comments):

if let resourceValues = try? url.resourceValues(forKeys: [.typeIdentifierKey]),
    let uti = resourceValues.typeIdentifier {
    return uti
}
pkamb
  • 33,281
  • 23
  • 160
  • 191
  • 1
    There is a difference in behaviour between the answers... This method getResourceValue:forKey:error: only works for File urls that exist. It gives an error if the file does not exist. The other answer using UTTypeCreatePreferredIdentifierForTag works just using the file extension without needing a physical file. – Steven Green Jan 21 '21 at 14:50