Home > Mobile >  MacOS how is KIND implemented
MacOS how is KIND implemented

Time:11-04

I am trying to write a piece of code that instead of checking file extensions for the many different types of image files, but instead looking at the file attributes. What I can’t figure out from searching the docs is if KIND:Image is really a file attribute or simply a construct Apple created in the FinderApp to make things easier for the user.

I wrote a snippet that pulls the attributes for files with an extension of jpeg and for each file the fileType is returned as NSFileTypeRegular.

let attr = try filemanager.attributesOfItem(atPath: pathConfig "/" file) as NSDictionary

if file.hasSuffix(ext) {

   print ("Adding \(file) [ \(attr.fileSize()) \(attr.fileType())]")

   print ( attr.fileModificationDate() )
}

Does anybody know if MacOS retains an attribute for the category a file falls in to. e.g. IMAGE, DOCUMENT etc.

CodePudding user response:

To achieve a functionality similar to the Kind search tag in Finder you can use UTType (Link to reference).

You can get the UTType of a file by initialising it with the file extension:

let fileType = UTType(filenameExtension: fileURL.pathExtension)

The cool thing about UTTypes is that they can have a hierarchy, so UTType.jpeg is a subtype of UTType.image.

If you want to check if a file is any kind of image, you can do it like this

let isImage = fileType.conforms(to: .image)

You can check the list for the kind of types you want to support as "Kinds", and filter using those UTTypes

CodePudding user response:

This was my final solution based on the information provided by @EmilioPelaez I am not completely comfortable with Swift especially the unwrapping operations so if the code looks weird that might be why.

func imagesInDir(path: String?) -> [String] {
    if let path {
        let filemanager: FileManager = FileManager()
        let files = filemanager.enumerator(atPath: path)
        var array = [String]()
        var urlFile: NSURL
        
        while let file = files?.nextObject() as? String {
            urlFile = NSURL(fileURLWithPath: file, isDirectory: false)
            if (urlFile.isFileURL) {
                if let pathExt = urlFile.pathExtension {
                    if let fileType = UTType(filenameExtension: pathExt) {
                        let isImage = fileType.conforms(to: .image)
                        if (isImage){
                            array.append(file)
                            print ("\(array.count)  \(fileType)")
                        }
                    }
                }
            }
        }
    }
    return array
}
  • Related