I am writing a method to get the MIME type from given file extension:
private class func mime(from utType: UTType) -> String? {
let mimeType: String
if let preferredMIMEType = utType.preferredMIMEType {
mimeType = preferredMIMEType
} else {
return nil
}
return mimeType
}
public class func convertToMime(fileExtension: String) -> String? {
var utType: UTType? = UTType(filenameExtension: fileExtension)
var mimeType: String?
if let utType = utType {
mimeType = mime(from: utType)
}
return mimeType
}
The test passes for txt and mp4 types, but not pkpass.
func testThatConvertToMimeConvertsFileExtensions() {
XCTAssertEqual(UTIHelper.convertToMime(fileExtension: "pkpass"), "application/vnd.apple.pkpass")
XCTAssertEqual(UTIHelper.convertToMime(fileExtension: "txt"), "text/plain")
XCTAssertEqual(UTIHelper.convertToMime(fileExtension: "mp4"), "video/mp4")
}
I tried to print the info of UTType and got these:
print(utType.description)
print(utType.tags)
print(utType.preferredMIMEType)
com.apple.pkpass-data
[public.filename-extension: ["pkpass"]]
nil
The default argument for the second parameter of the
UTTypeinitialiser that you are using is.data:So this finds a
UTTypethat is a subtype ofpublic.data. However, TheUTTypethat you want (com.apple.pkpass) does not havepublic.dataas a super type (i.e. does not conform topublic.data). In fact, a.pkpassfile is sort of like a.frameworkfile - it's a bundle/package of things. (Try extracting its contents with The Unarchiver!) This is why the initialiser does not find the correctUTType.Learn more about the hierarchies of
UTTypes here.You can use this other initialiser, and pass
nilto theconformingToargument. This will find you anyUTTypethat has the specified file name:Also note the warning in the docs: