通过统一类型标识符选择UIImage

时间:2017-11-08 18:00:58

标签: ios swift uiimage uti

在我的iOS应用中,我必须在UITableView中列出文档,并且我想将它们与UIImage相关联。要选择图像,我必须遵循这个方案

  • IMAGE1 - 扩展程序 .doc .docx .ott .odt .DOT
  • IMAGE2 - 扩展名为 .pdf
  • 的文件
  • IMAGE3 - 扩展程序 .xls xlsx .ods
  • 的文件

如何在UIImage iOS框架中使用统一类型标识符来选择正确的MobileCoreServices

我写了以下swift函数:

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.
        }
    }

我使用FileKit来管理我的文件'路径。我的cellForRowAt看起来像

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
}

我发现image功能非常难看。有没有更聪明的方法来实现我的目标?

感谢。

0 个答案:

没有答案