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

倾然丶 夕夏残阳落幕 提交于 2019-12-01 00:03:56

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!