1

In my current application I am downloading few files from server, and storing them locally.

Based on extension of file I am loading the file in appropriate view.

Example:

  1. file extensions: mov, 3gp, m4a, etc., => display in media player.
  2. file extensions: rtf, pptx, numbers, etc., =>display in UIWebView.
  3. file extensions: gif, png, xbm, etc., =>display in UIImageView.

Problem is: some of the downloaded files may not have any extension.

One approach which I found is- in connectionDidFinishLoading obtain MIMEType from response and from that obtain file extension. I used below code, for the same:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    CFStringRef mimeType = (__bridge CFStringRef)[_respo MIMEType];
    CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType, NULL);
    CFStringRef extension = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension);
    NSString *fileName = [NSString stringWithFormat:@"%@.%@", [[_respo suggestedFilename] stringByDeletingPathExtension], (__bridge NSString *)extension];
    [[NSFileManager defaultManager] createFileAtPath:[[self docsDir] stringByAppendingPathComponent:[NSString stringWithFormat:@"Downloads/%@", fileName]] contents:_downloadedData attributes:nil];
}

Now my questions are:

  1. Is there any other way to identify file extension for the files without extensions, say from NSData object?

  2. In place of checking file extension, is there any other way to show the file in appropriate view?

Please suggest.

Devarshi
  • 16,440
  • 13
  • 72
  • 125
  • It may be easiest to use `QLPreviewController` will all of the files. Then you don't need to work about file extensions and file types and the user gets a consistent user experience for all files. – rmaddy Sep 29 '13 at 03:24

2 Answers2

0

A common non-Objective-C way to do this is using the file command, which looks for "magic" portions of the file to determine/guess/estimate it's mime type.

It's written in C, so depending on how much the feature is worth to you, you could potentially integrate it in.

Source: http://darwinsys.com/file/ Man page: http://www.openbsd.org/cgi-bin/man.cgi?query=file&apropos=0&sektion=1

Brad Peabody
  • 10,917
  • 9
  • 44
  • 63
0

As a different approach - can you not simply look at the Content-type header of the connection you are using to download? If the server knows the mime type, that would seem to be a good solution. (If the server does not know the mime type but you have control of it, try installing: http://httpd.apache.org/docs/2.2/mod/mod_mime_magic.html or equivalent.)

Brad Peabody
  • 10,917
  • 9
  • 44
  • 63