将mimetype转换为文件扩展名

时间:2014-07-10 14:17:30

标签: xcode nsurlconnection mime-types file-extension

如何在xcode中将mimetype转换为文件扩展名 例如,我有这个代码

File Extension     MIME Type

aifc                audio/x-aiff
avi                 video/x-msvideo
gz                  application/x-gzip
jpg                 image/jpeg

的Xcode

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
        NSString *mime      = [response MIMEType];
        NSString *extension = @"" // how to covert it ?!
}

2 个答案:

答案 0 :(得分:4)

包括<MobileCoreServices/MobileCoreServices.h><CoreServices/CoreServices.h> 然后只需遵循以下代码:

CFStringRef mimeType = (CFStringRef)@"audio/x-aiff";
CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType, NULL);
CFStringRef extension = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension);

答案 1 :(得分:2)

Swift 4:

导入CoreServices

response.mimeType // is Optional<String> - some : "audio/mpeg"

如何获取mp3是:

guard let mime = response.mimeType,
      let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mime as CFString, nil),
      let ext = UTTypeCopyPreferredTagWithClass(uti.takeRetainedValue(), kUTTagClassFilenameExtension) else{
   return
}

ext.takeRetainedValue() // is "mp3"
PD:考虑到Xcode不会得到像.Storyboard或.cert这样的未知文件的扩展,在这种情况下会在Guard返回中退出。