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

后端 未结 9 1634
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  孤城傲影
    2020-12-01 02:51

    I was using the answer provided by slf in a cocoa app (not iPhone) and noticed that the URL request seems to be reading the entire file from disk in order to determine the mime type (not great for large files).

    For anyone wanting to do this on the desktop here is the snippet I used (based on Louis's suggestion):

    NSString *path = @"/path/to/some/file";
    
    NSTask *task = [[[NSTask alloc] init] autorelease];
    [task setLaunchPath: @"/usr/bin/file"];
    [task setArguments: [NSArray arrayWithObjects: @"-b", @"--mime-type", path, nil]];
    
    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    
    NSFileHandle *file = [pipe fileHandleForReading];
    
    [task launch];
    [task waitUntilExit];
    if ([task terminationStatus] == YES) {
        NSData *data = [file readDataToEndOfFile];
        return [[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] autorelease];
    } else {
        return nil;
    }
    

    If you called that on a PDF file it would spit out: application/pdf

提交回复
热议问题