macOS 获取当前活动的应用程序

监听当前活动的应用程序,获取图标和名称

Posted by Yang on August 1, 2021

之前有这么一个需求:

监听剪贴板的变化,记录复制的历史记录,需要知道剪贴板的复制来源,保存来源APP的名字和图标。

macOS 有提供相应的 API,NSWorkspace

获取 icon 的 NSImage -> tiffRepresentation 方法转为 Data -> 使用 NSBitmapImageRep 可以转为 png 和 jpeg 等格式,只有 .jpeg 格式可以用 representation 中的 properties 进行压缩。

1
2
3
4
5
6
7
if let frontApp = NSWorkspace.shared.frontmostApplication, let appName = frontApp.localizedName, let iconImage = frontApp.icon, let tiffData = iconImage.tiffRepresentation, let imageRep = NSBitmapImageRep(data: tiffData), let pngData = imageRep.representation(using: .jpeg, properties: [.compressionFactor:"0.1"]) {

        let imageName = appName + ".jpg"
        let filePath = getDocumentsDirectory().appendingPathComponent(imageName)
        try? pngData.write(to: filePath)
    }