Search code examples
macoscocoadesktopnsworkspace

How do I programmatically change system-wide desktop picture?


I'm using the following code to set desktop picture:

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

It works fine and the desktop picture changed as I required. But it does not change the system-wide desktop preferences (for example, change picture every 30 minutes). How can I change the system-wide desktop preferences?


Solution

  • Take a look at Preferences and Settings Programming Guide. This should help.

    Edit:
    Here is the sample code:

    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");