How can you read a files MIME-type in objective-c

后端 未结 9 1641
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 01:50

I am interested in detecting the MIME-type for a file in the documents directory of my iPhone application. A search through the docs did not provide any answers.

9条回答
  •  猫巷女王i
    2020-12-01 02:46

    The accepted answer is problematic for large files, as others have mentioned. My app deals with video files, and loading an entire video file into memory is a good way to make iOS run out of memory. A better way to do this can be found here:

    https://stackoverflow.com/a/5998683/1864774

    Code from above link:

    + (NSString*) mimeTypeForFileAtPath: (NSString *) path {
      if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return nil;
      }
      // Borrowed from https://stackoverflow.com/questions/5996797/determine-mime-type-of-nsdata-loaded-from-a-file
      // itself, derived from  https://stackoverflow.com/questions/2439020/wheres-the-iphone-mime-type-database
      CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)[path pathExtension], NULL);
      CFStringRef mimeType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
      CFRelease(UTI);
      if (!mimeType) {
        return @"application/octet-stream";
      }
      return [NSMakeCollectable((NSString *)mimeType) autorelease];
    }
    

提交回复
热议问题