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

前端 未结 1 1016
心在旅途
心在旅途 2021-01-06 11:48

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

相关标签:
1条回答
  • 2021-01-06 12:37

    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.

    0 讨论(0)
提交回复
热议问题