如何以编程方式更改系统范围的桌面图片?

时间:2013-07-14 07:47:23

标签: macos cocoa desktop nsworkspace

我正在使用以下代码设置桌面图片:

NSURL* newImage = [[NSURL alloc] initFileURLWithPath:@"/Users/name/Pictures/test.png"];
[[NSWorkspace sharedWorkspace] setDesktopImageURL:newImage forScreen:screen options:nil error:&nserror];

它工作正常,桌面图片按我的要求更改。但它不会改变系统范围的桌面首选项(例如,每隔30分钟更改一次图片)。如何更改系统范围的桌面首选项?

1 个答案:

答案 0 :(得分:0)

看看Preferences and Settings Programming Guide。这应该有所帮助。

修改
以下是示例代码:

NSString* newImgPath = @"/Users/cody/Desktop/stuff/imgs/Black_mac.png";

NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary* desktopDict = [NSMutableDictionary dictionaryWithDictionary:[defaults persistentDomainForName:@"com.apple.desktop"]];
NSMutableDictionary* bgDict = [desktopDict objectForKey:@"Background"];
NSMutableDictionary* spaces = [bgDict objectForKey:@"spaces"];
[spaces enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSMutableDictionary* obj, BOOL *stop) {
    [obj enumerateKeysAndObjectsUsingBlock:^(id key, NSMutableDictionary* prefs, BOOL *stop) {
        [prefs setObject:newImgPath forKey:@"ImageFilePath"];
        [prefs setObject:newImgPath forKey:@"NewImageFilePath"];
        [prefs setObject:@"Never" forKey:@"Change"];
    }];
}];

//NSLog(@"%@", desktopDict);

[defaults setPersistentDomain:desktopDict forName:@"com.apple.desktop"];
if ([defaults synchronize] == NO)
    NSLog(@"synchronize failed");

// Restart dock
system ("/usr/bin/killall Dock");