Added optional MIME Type auto-detection using MobileCoreServices

This commit is contained in:
Blake Watters
2010-10-27 14:54:37 -04:00
parent 0d8bc8c92d
commit 8fef65e4df
2 changed files with 36 additions and 8 deletions

View File

@@ -6,6 +6,7 @@
// Copyright 2009 Two Toasters. All rights reserved.
//
#import <MobileCoreServices/UTType.h>
#import "RKParamsAttachment.h"
/**
@@ -13,6 +14,10 @@
*/
extern NSString* const kRKStringBoundary;
@interface RKParamsAttachment (Private)
- (NSString *)mimeTypeForExtension:(NSString *)extension;
@end
@implementation RKParamsAttachment
@synthesize fileName = _fileName, MIMEType = _MIMEType, name = _name;
@@ -51,17 +56,16 @@ extern NSString* const kRKStringBoundary;
}
- (id)initWithName:(NSString*)name file:(NSString*)filePath {
if (self = [self initWithName:name]) {
_fileName = [filePath lastPathComponent];
_MIMEType = @"application/octet-stream"; // TODO: Add MIME type auto-detection!
// TODO: [self mimeTypeForExtension:[path pathExtension] -> default the MIMEType
_bodyStream = [[NSInputStream inputStreamWithFileAtPath:filePath] retain];
if (self = [self initWithName:name]) {
NSAssert1([[NSFileManager defaultManager] fileExistsAtPath:filePath], @"Expected file to exist at path: %@", filePath);
_fileName = [filePath lastPathComponent];
_MIMEType = [self mimeTypeForExtension:[filePath pathExtension]];
_bodyStream = [[NSInputStream inputStreamWithFileAtPath:filePath] retain];
NSError* error = nil;
_bodyLength = [[[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error] objectForKey:NSFileSize] unsignedIntegerValue];
if (error) {
NSLog(@"Encountered an error while determining file size: %@");
NSLog(@"Encountered an error while determining file size: %@", error);
}
}
@@ -86,6 +90,25 @@ extern NSString* const kRKStringBoundary;
return kRKStringBoundary;
}
- (NSString *)mimeTypeForExtension:(NSString *)extension {
if (NULL != UTTypeCreatePreferredIdentifierForTag) {
CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)extension, NULL);
if (uti != NULL) {
CFStringRef mime = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType);
CFRelease(uti);
if (mime != NULL) {
NSString *type = [NSString stringWithString:(NSString *)mime];
CFRelease(mime);
return type;
}
}
}
return @"application/octet-stream";
}
#pragma mark NSStream methods
- (void)open {
// Generate the MIME header for this part
if (self.fileName && self.MIMEType) {