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

后端 未结 9 1625
伪装坚强ぢ
伪装坚强ぢ 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:57

    Based on the Lawrence Dol/slf answer above, I have solved the NSURL loading the entire file into memory issue by chopping the first few bytes into a head-stub and getting the MIMEType of that. I have not benchmarked it, but it's probably faster this way too.

    + (NSString*) mimeTypeForFileAtPath: (NSString *) path {
        // NSURL will read the entire file and may exceed available memory if the file is large enough. Therefore, we will write the first fiew bytes of the file to a head-stub for NSURL to get the MIMEType from.
        NSFileHandle *readFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
        NSData *fileHead = [readFileHandle readDataOfLength:100]; // we probably only need 2 bytes. we'll get the first 100 instead.
    
        NSString *tempPath = [NSHomeDirectory() stringByAppendingPathComponent: @"tmp/fileHead.tmp"];
    
        [[NSFileManager defaultManager] removeItemAtPath:tempPath error:nil]; // delete any existing version of fileHead.tmp
        if ([fileHead writeToFile:tempPath atomically:YES])
        {
            NSURL* fileUrl = [NSURL fileURLWithPath:path];
            NSURLRequest* fileUrlRequest = [[NSURLRequest alloc] initWithURL:fileUrl cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:.1];
    
            NSError* error = nil;
            NSURLResponse* response = nil;
            [NSURLConnection sendSynchronousRequest:fileUrlRequest returningResponse:&response error:&error];
            [[NSFileManager defaultManager] removeItemAtPath:tempPath error:nil];
            return [response MIMEType];
        }
        return nil;
    }
    

提交回复
热议问题