如何获得Mac当前壁纸完整路径及名称的一个脚本
我写了一个脚本可以获得当前壁纸路径及名称的,但是我晕了,这个脚本是可以获得前一个壁纸和当前壁纸和后一个壁纸的名称的,但是我不想搞了,希望有人可以完善。
此脚本在 macos15.6,macbookair上测试通过。
#!/usr/bin/env swift
import AppKit
import Foundation
// MARK: - 工具函数
func expandTilde(_ path: String) -> String {
if path.hasPrefix("~") { return (path as NSString).expandingTildeInPath }
return path
}
func isDirectory(_ path: String) -> Bool {
var isDir: ObjCBool = false
let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDir)
return exists && isDir.boolValue
}
func isFile(_ path: String) -> Bool {
var isDir: ObjCBool = false
let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDir)
return exists && !isDir.boolValue
}
@discardableResult
func runShell(_ command: String) -> (status: Int32, stdout: String, stderr: String) {
let task = Process()
task.executableURL = URL(fileURLWithPath: "/bin/zsh")
task.arguments = ["-lc", command]
let outPipe = Pipe()
let errPipe = Pipe()
task.standardOutput = outPipe
task.standardError = errPipe
do { try task.run() } catch {
return (status: -1, stdout: "", stderr: "执行失败: \(error)")
}
task.waitUntilExit()
let outData = outPipe.fileHandleForReading.readDataToEndOfFile()
let errData = errPipe.fileHandleForReading.readDataToEndOfFile()
let outStr = String(data: outData, encoding: .utf8) ?? ""
let errStr = String(data: errData, encoding: .utf8) ?? ""
return (status: task.terminationStatus, stdout: outStr, stderr: errStr)
}
// 通过 System Events 获取当前桌面图片路径(可能返回目录)
func getSystemEventsDesktopPicture() -> String? {
let source = """
tell application "System Events"
tell current desktop
set wallpaperPath to picture
end tell
end tell
"""
var errorInfo: NSDictionary?
guard let script = NSAppleScript(source: source) else { return nil }
let result = script.executeAndReturnError(&errorInfo)
if errorInfo != nil { return nil }
return result.stringValue
}
// 通过 Finder 获取当前桌面图片的完整信息
func getFinderDesktopPictureInfo() -> (name: String?, path: String?) {
let source = """
tell application "Finder"
try
set theDesktopPic to desktop picture
set theName to displayed name of theDesktopPic
set thePath to POSIX path of theDesktopPic
return {theName, thePath}
on error errMsg
return {"", ""}
end try
end tell
"""
var errorInfo: NSDictionary?
guard let script = NSAppleScript(source: source) else { return (nil, nil) }
let result = script.executeAndReturnError(&errorInfo)
if errorInfo != nil { return (nil, nil) }
let output = result.stringValue ?? ""
let components = output.components(separatedBy: ", ")
let name = components.first?.trimmingCharacters(in: .whitespacesAndNewlines)
let path = components.count > 1 ? components[1].trimmingCharacters(in: .whitespacesAndNewlines) : nil
return (name, path)
}
// 获取目录中最可能是当前壁纸的文件
func getCurrentWallpaperFile(in directory: String) -> String? {
guard let urls = try? FileManager.default.contentsOfDirectory(
at: URL(fileURLWithPath: directory),
includingPropertiesForKeys: [.contentAccessDateKey, .contentModificationDateKey, .creationDateKey, .fileSizeKey],
options: [.skipsHiddenFiles]
) else { return nil }
let imageExts: Set<String> = ["jpg","jpeg","png","heic","tiff","bmp","gif","webp"]
let candidates = urls.filter { !$0.hasDirectoryPath && imageExts.contains($0.pathExtension.lowercased()) }
// 多种策略来找到当前壁纸
var bestCandidate: URL? = nil
var bestScore = -1
for url in candidates {
var score = 0
// 策略1: 最近修改的文件得分更高
if let modDate = try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate {
let hoursSinceMod = Date().timeIntervalSince(modDate) / 3600
if hoursSinceMod < 24 { score += 10 } // 24小时内修改
else if hoursSinceMod < 168 { score += 5 } // 一周内修改
}
// 策略2: 文件大小适中的图片(排除过小或过大的文件)
if let fileSize = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize {
let sizeMB = Double(fileSize) / 1024 / 1024
if sizeMB >= 0.1 && sizeMB <= 10.0 { score += 5 } // 100KB-10MB
else if sizeMB > 10.0 { score += 2 } // 大于10MB
}
// 策略4: 最近创建的文件得分更高
if let createDate = try? url.resourceValues(forKeys: [.creationDateKey]).creationDate {
let hoursSinceCreate = Date().timeIntervalSince(createDate) / 3600
if hoursSinceCreate < 24 { score += 3 }
}
if score > bestScore {
bestScore = score
bestCandidate = url
}
}
return bestCandidate?.path
}
[标题经过版主编辑] 原标题: 如何获得当前壁纸完整路径及名称
MacBook Air, macOS 15.6