如何使用Swift在MacOS上检查文件是否有红色标签标签在Finder中?

huangapple go评论145阅读模式
英文:

How can I check if a file has a red tag label in Finder using Swift on MacOS?

问题

我正在为 MacOs 创建我的第一个项目。
我必须处理文件夹中的文件。我的目标是检查这些文件,并查看哪些元素通过 Finder 应用了红色标签。
我真的疯了,因为代码无法识别具有红色标签的图像。

这是我编写的函数。

这是 ViewController 中的代码。

文件信息

英文:

I am creating my first project for MacOs.
I have to work on files in a folder. My goal is to check these files and see which elements have a red tag applied via Finder.
I am literally going crazy because the code cannot recognise the images with the red tag.

This is the function I have written.

 func isFileTaggedRed(at fileURL: URL) -> Bool {
        do {
            let resourceValues = try fileURL.resourceValues(forKeys: [.labelColorKey])
            if let labelColor = resourceValues.labelColor, labelColor == .red {
                return true
            }
        } catch {
            print("Error retrieving resource values for file: \(error)")
        }
        
        return false
    }

This is the code in the ViewController

for imageUrl in imageUrls {
            if isFileTaggedRed(at: imageUrl) {
                print("Skipping red tagged image: \(imageUrl.lastPathComponent)")
                continue
            }else{
                print("not tagged")
            }
        }

file info

答案1

得分: 2

我不知道是否有更简单的方法来完成您所需的操作,但您可以获取文件的tagNames并检查是否包含"Red"

extension URL {
    var isFileTaggedRed: Bool {
        tagNames.contains("Red")
    }
    var tagNames: [String] {
        (try? resourceValues(forKeys: [.tagNamesKey]))?.tagNames ?? []
    }
}

用法:

import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let folderUrl = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!
            .appendingPathComponent("untitled folder", isDirectory: true)

        let files = try! FileManager.default.contentsOfDirectory(at: folderUrl, includingPropertiesForKeys: nil)

        if let fileUrl = files.first {
            print("isTaggedRed:", fileUrl.isFileTaggedRed)
        }
    }
}
英文:

I don't know if there is an easier way to accomplish what you need but you can get the fileUrl tagNames and check if it contains "Red"


extension URL {
    var isFileTaggedRed: Bool {
        tagNames.contains("Red")
    }
    var tagNames: [String] {
        (try? resourceValues(forKeys: [.tagNamesKey]))?.tagNames ?? []
    }
}

Usage:

import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let folderUrl = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!
            .appendingPathComponent("untitled folder", isDirectory: true)

        let files = try! FileManager.default.contentsOfDirectory(at: folderUrl, includingPropertiesForKeys: nil)

        if let fileUrl = files.first {
            print("isTaggedRed:", fileUrl.isFileTaggedRed)
        }
    }
}

答案2

得分: 1

I haven't used labelColorKey before. It looks like the labelColor you get back is an NSColor. Colors are tricky in a color-managed system like MacOS. The color may be a shade of red but not the exact color you want. I would suggest logging the RGB values of your returned colors with NSColor.getRed(_:green:blue:alpha:). You're probably getting back a color that's close to, but not exactly equal to .red.

You might need to add code that checks to see if the RGB values are within a "wiggle room" range of .red (say each component is within .01 of the target color.)

Edit:

I just tried it, and when I added a red label to a file, I got back an NSColor that logs as NSCalibratedRGBColorSpace 0.980484 0.382818 0.347662 1

That will look red, but not fully saturated red.

Note that NSColor.red logs as sRGB IEC61966-2.1 colorspace 1 0 0 1 (100% red and no green or blue.)

Furthermore, when I look at a file with a red label, it does look like a slightly washed out red, not pure red.

Edit #2:

The code I used (in a command line tool) is as follows:

func fileColor(at fileURL: URL) -> NSColor? {
   do {
       let resourceValues = try fileURL.resourceValues(forKeys: [.labelColorKey])
       if let labelColor = resourceValues.labelColor {
           return labelColor
       }
   } catch {
       print("Error retrieving resource values for file: \(error)")
       return nil
   }
   
   return nil
}

let path = "~/Documents/RedFile.rtf"
let fixedPath = NSString(string: path).expandingTildeInPath
let fileURL = URL(filePath: fixedPath)

if let fileColor = fileColor(at: fileURL) {
    print("File color returned is \(fileColor)")
} else {
    print("Could not load file.")
}

(Note: I didn't translate the code, as requested.)

英文:

I haven't used labelColorKey before. It looks like the labelColor you get back is an NSColor. Colors are tricky in a color-managed system like MacOS. The color may be a shade of red but not the exact color you want. I would suggest logging the RGB values of your returned colors with NSColor.getRed(_:green:blue:alpha:). You're probably getting back a color that's close to, but not exactly equal to .red.

You might need to add code that checks to see if the RGB values are within a "wiggle room" range of .red (say each component is within .01 of the target color.)

Edit:

I just tried it, and when I added a red label to a file, I got back an NSColor that logs as NSCalibratedRGBColorSpace 0.980484 0.382818 0.347662 1

That will look red, but not fully saturated red.

Note that NSColor.red logs as sRGB IEC61966-2.1 colorspace 1 0 0 1 (100% red and no green or blue.)

Furthermore, when I look at a file with a red label, it does look like a slightly washed out red, not pure red.

Edit #2:

The code I used (in a command line tool) is as follows:

func fileColor(at fileURL: URL) -> NSColor? {
       do {
           let resourceValues = try fileURL.resourceValues(forKeys: [.labelColorKey])
           if let labelColor = resourceValues.labelColor {
               return labelColor
           }
       } catch {
           print("Error retrieving resource values for file: \(error)")
           return nil
       }
       
       return nil
   }

let path = "~/Documents/RedFile.rtf"
let fixedPath = NSString(string:path).expandingTildeInPath
let fileURL = URL(filePath: fixedPath)

if let fileColor = fileColor(at: fileURL) {
    print("File color returned is \(fileColor)")
} else {
    print("Could not load file.")
}

huangapple
  • 本文由 发表于 2023年5月29日 22:56:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76358359.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定