How to get the path to the current workspace/screen's wallpaper on OSX?

1.6k views Asked by At

Since AppKit version 10.7, NSWorkspace.desktopImageForScreen may return a path to a folder instead of a file's URL which is currently the wallpaper. This folder is the the place from where the wallpapers will be sequentially picked up for display. (Search for setDesktopImageURL in the release notes).

In case the user has set the desktop image to change randomly every thirty minutes or so, is there any way of determining what are the currently active wallpapers per screen in OSX?


Update: Based no the answer by @l'L'l, I created a small Mac OSX app to conveniently find the currently active Wallpapers: https://github.com/musically-ut/whichbg

1

There are 1 answers

2
l'L'l On BEST ANSWER

On OS X 10.10 there is a SQLite 3.x database named desktoppicture.db. This db file stores info such as the current desktop picture, directory, space, interval, etc. when a timed random desktop picture transition happens or when there's any change to System Preferences > Desktop:

Objective-C

// Get Current Desktop Picture

- (IBAction)getDesktopPicture:(id)sender {

    [self getCurrentDesktop];
}

-(void)getCurrentDesktop {

    NSMutableArray *sqliteData = [[NSMutableArray alloc] init];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
    NSString *appSup = [paths firstObject];
    NSString *dbPath = [appSup stringByAppendingPathComponent:@"Dock/desktoppicture.db"];

    sqlite3 *database;
    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {

        const char *sql = "SELECT * FROM data";
        sqlite3_stmt *sel;
        if(sqlite3_prepare_v2(database, sql, -1, &sel, NULL) == SQLITE_OK) {

            while(sqlite3_step(sel) == SQLITE_ROW) {
                NSString *data = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sel, 0)];
                [sqliteData addObject:data];
            }
        }
    }
    NSUInteger cnt = [sqliteData count] - 1;
    NSLog(@"Desktop Picture: %@", sqliteData[cnt]);
    NSLog(@"%@",sqliteData);

    sqlite3_close(database); 
}

Result:

2015-06-23 14:36:04.470 CurrentDesktop[72591:87862519] Desktop Picture: Poppies.jpg 2015-06-23 14:36:04.470 CurrentDesktop[72591:87862519] ( "60.0", 1, "Poppies.jpg" )

There are quite a few different other ways you can get the data from this file (eg. NSTask, Bash, AppleScript, etc. This is my preferred solution since it's native mac code; it's simple enough to make portable for something else though.