私は現在の壁紙を取得するためにこのコードを使用しています:
NSURL *imageURL = [[NSWorkspace sharedWorkspace] desktopImageURLForScreen:[NSScreen mainScreen]];
これは問題なく動作しますが、写真のフォルダを壁紙に設定すると(写真に示すように)、imageURL
はディレクトリになります。この状況で現在の壁紙のUSURLを取得するにはどうすればよいですか?
現在の壁紙のスクリーンショットを撮って画像を取得する別の方法があります。
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
}
}
URLではなく画像が必要な場合、このアプローチははるかに単純なIMHOに見えます。
壁紙はcom.apple.dektopplistで定義されていないことに注意してください。Mavericksから開始して、設定は〜/ Library / Application Support / Dock/desktoppicture.dbに移動されます。これはSQLiteファイルであり、「データ」テーブルにはURLが含まれています。
私はまったく同じことをしようとしてきました。現在のデスクトップ画像のURLは、次の方法で取得できます。
私はまだこれに取り組んでいますが、次のコードは正しいURLを取得します...時々。主な問題は、プロパティリストが十分な頻度で更新されておらず、(ドックを強制終了するまで)強制的に更新することができなかったことです。あなたが何かを理解したら私に知らせてください!
NSDictionary *spacesPLIST = (__bridge NSDictionary *)(CFPreferencesCopyAppValue(CFSTR("SpacesConfiguration"), CFSTR("com.apple.spaces")));
NSDictionary *desktopPLIST = (__bridge NSDictionary *)(CFPreferencesCopyAppValue(CFSTR("Background"), CFSTR("com.apple.desktop")));
NSArray *monitors = [spacesPLIST valueForKeyPath:@"Management Data.Monitors"];
NSInteger monitorIndex = 0;
if ([monitors count] > 1) {
//search for main (or ask user to select)
}
NSDictionary *monitor = [monitors objectAtIndex:monitorIndex];
NSDictionary *spaces = [desktopPLIST valueForKey:@"spaces"];
NSString *currentSpaceUUID = [monitor valueForKeyPath:@"Current Space.uuid"];
NSDictionary *currentSpace = [spaces valueForKey:currentSpaceUUID];
NSURL *desktopPicturesDirectory = [NSURL fileURLWithPath:[currentSpace valueForKeyPath:@"default.ChangePath"] isDirectory:true];
NSString *desktopPictureName = [currentSpace valueForKeyPath:@"default.LastName"];
NSURL *desktopPictureURL = [NSURL URLWithString:desktopPictureName relativeToURL:desktopPicturesDirectory];
[[NSWorkspace sharedWorkspace] selectFile:[desktopPictureURL path] inFileViewerRootedAtPath:@""];