In my iOS app I have to list documents in a UITableView
and I want to associate them an UIImage
. To choose image I have to follow this scheme
- IMAGE1 - file with extension .doc, .docx, .ott, .odt, .dot
- IMAGE2 - file with extension .pdf
- IMAGE3 - file with extension .xls, xlsx, .ods
- etc.
How can I choose the right UIImage
by using Uniform Type Identifiers in MobileCoreServices
iOS framework?
I write the following swift function:
public static func image(for pathExtension: String) -> UIImage {
guard let rawUtis = UTTypeCreateAllIdentifiersForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue() as? [String] else {
return #imageLiteral(resourceName: "UNKNOWN")
}
for rawUti in rawUtis {
if UTTypeConformsTo(rawUti as CFString, kUTTypePDF) {
return #imageLiteral(resourceName: "IMAGE2")
}
if UTTypeConformsTo(rawUti as CFString, "com.microsoft.word.doc") || UTTypeConformsTo(rawUti as CFString, "org.openxmlformats.wordprocessingml.document") || UTTypeConformsTo(rawUti as CFString, "org.oasis-open.opendocument.text-template") || UTTypeConformsTo(rawUti as CFString, "org.oasis-open.opendocument.text") || UTTypeConformsTo(rawUti as CFString, "com.microsoft.word.dot") {
return #imageLiteral(resourceName: "IMAGE1")
}
// etc.
}
}
I'm using FileKit to manage my documents' paths. My cellForRowAt
looks like
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "documentCell", for: indexPath) as! DocumentViewCell
let documentPath = ... // document's path from indexPath
cell.nameLabel.text = documentPath.fileName
cell.iconImageView?.image = UTI.image(for: documentPath.pathExtension)
// ...
return cell
}
I find image
function very ugly. Is there a smarter way to achieve my goal?
Thanks.