Search code examples
swiftappkit

How can I determine multiple finder (color) labels


I am trying to determine all of the color labels on a directory. When I check the URLResourceValues of a directory URL it only seems to return the "top" or most recent one, however a directory can have more than one label.

Here is the URL extension code I'm using to return the label from a URL:

extension URL {
    func hasFinderLabel() -> ColorLabel {
        let folder = self
        var rVals = URLResourceValues()
        do {
            rVals = try folder.resourceValues(forKeys: [.labelNumberKey, .labelColorKey])
        } catch {}
        if let colorLabels = rVals.labelColor {
            print(colorLabels)
        }
        let colorNumber : Int = rVals.labelNumber ?? 0
        var colorLabel : ColorLabel
        switch colorNumber {
        case 0:
            colorLabel = .none
        case 1:
            colorLabel = .gray
        case 2:
            colorLabel = .green
        case 3:
            colorLabel = .purple
        case 4:
            colorLabel = .blue
        case 5:
            colorLabel = .yellow
        case 6:
            colorLabel = .red
        case 7:
            colorLabel = .orange
        default:
            colorLabel = .none
        }
        return colorLabel
    }
}

enum ColorLabel : Int {
    case none
    case gray
    case green
    case purple
    case blue
    case yellow
    case red
    case orange
}

If a directory has more than one color label this only returns one of them – the top most.


Solution

  • You are accessing the incorrect resource value. To get the colors applied to a file you need the tagNames resource. This returns a String array with the color names as well as any other tags applied to the file.

    let rVals = try folder.resourceValues(forKeys: [.tagNamesKey])
    if let tags = rVals.tagNames {
        print(tags)
    } else {
        print("No tags")
    }
    

    tags will contain values such as "Red", "Green", etc. depending on the colors applied to the file. The colors are just tags.