0

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.

Giorgio
  • 1,973
  • 4
  • 36
  • 51
  • Why do you need a UTI? You have the file extension. Just write a `switch` for the different possible extensions. – rmaddy Nov 08 '17 at 18:17
  • I don't understand why this question has been closed as duplicate... I doesn't think the linked post answers my question. – Giorgio Nov 08 '17 at 19:38
  • You just need to get the typeIdentifier from your file url. Where are you getting your pathExtension from? just switch the typeIdentifier from the url. – Leo Dabus Nov 08 '17 at 20:15
  • Thanks @LeoDabus. Could you be more specific? How do I find right image from typeIdentifier? – Giorgio Nov 08 '17 at 20:26
  • Can you edit your question and show how you are calling this method? – Leo Dabus Nov 08 '17 at 20:27
  • @LeoDabus I edited my question. Thank you for your help. – Giorgio Nov 09 '17 at 08:53

0 Answers0