Có một cách khác để tải hình ảnh bằng cách chụp ảnh màn hình của hình nền hiện tại.
extension NSImage {
static func desktopPicture() -> NSImage {
let windows = CGWindowListCopyWindowInfo(
CGWindowListOption.OptionOnScreenOnly,
CGWindowID(0))! as NSArray
var index = 0
for var i = 0; i < windows.count; i++ {
let window = windows[i]
// we need windows owned by Dock
let owner = window["kCGWindowOwnerName"] as! String
if owner != "Dock" {
continue
}
// we need windows named like "Desktop Picture %"
let name = window["kCGWindowName"] as! String
if !name.hasPrefix("Desktop Picture") {
continue
}
// wee need the one which belongs to the current screen
let bounds = window["kCGWindowBounds"] as! NSDictionary
let x = bounds["X"] as! CGFloat
if x == NSScreen.mainScreen()!.frame.origin.x {
index = window["kCGWindowNumber"] as! Int
break
}
}
let cgImage = CGWindowListCreateImage(
CGRectZero,
CGWindowListOption(arrayLiteral: CGWindowListOption.OptionIncludingWindow),
CGWindowID(index),
CGWindowImageOption.Default)!
let image = NSImage(CGImage: cgImage, size: NSScreen.mainScreen()!.frame.size)
return image
}
}
Cách tiếp cận này trông đơn giản hơn IMHO, nếu bạn cần hình ảnh, không phải url.
Lưu ý rằng hình nền không còn được xác định trong danh sách com.apple.dektop: bắt đầu từ Mavericks, cài đặt được chuyển đến ~/Library/Application Support/Dock/desktoppicture.db. Đây là tệp SQLite và bảng "dữ liệu" chứa url.
Nguồn
2015-10-03 01:38:57
Tôi đã mở https://openradar.appspot.com/radar?id=5782854294306816 vì sẽ tốt hơn nếu API thực hiện những gì nó hứa hẹn. –