Notification when desktop wallpaper changes?
Asked Answered
C

2

6

is there any kind of notification available for when the desktop wallpaper is changed?

Thanks!

Coeternal answered 15/4, 2011 at 6:15 Comment(0)
E
2
[[NSDistributedNotificationCenter defaultCenter] addObserver:target
    selector:@selector(desktopImageChanged:)
    name:@"com.apple.desktop"
    object:@"BackgroundChanged"];

should to the job

Enfilade answered 15/4, 2011 at 10:12 Comment(2)
anyone has a replacement for this ? APPRECIATE IT !Crofter
This doesn't work on macOS 12 (Monterey)Loper
S
0
import Cocoa

class ViewController: NSViewController {
let checkInterval: TimeInterval = 1.0
// Adjust this interval as needed
// Create an instance of WallpaperObserver to start monitoring
let observer = WallpaperObserver()

override func viewDidLoad() {
    super.viewDidLoad()
    
    // Initial check
    observer.checkWallpaper()
    
    // Schedule periodic checks using a background queue
    DispatchQueue.global(qos: .background).async {
        self.startPeriodicCheck()
    }
}

func startPeriodicCheck() {
    // Perform periodic checks
    while true {
        Thread.sleep(forTimeInterval: checkInterval)
        DispatchQueue.main.async {
            self.observer.checkWallpaper()
        }
    }
  }
}

WallpaperObserver.swift

import Foundation
import Cocoa

class WallpaperObserver {

   var lastWallpaperPath: String?

   func checkWallpaper() {
    DispatchQueue.global(qos: .background).async {
        if let currentWallpaperPath = self.getCurrentWallpaperPath() {
            DispatchQueue.main.async {
                self.handleWallpaperChange(newPath: currentWallpaperPath)
            }
        } else {
            print("Failed to get current wallpaper path.")
        }
     }
  }

  func getCurrentWallpaperPath() -> String? {
    // Get the screen with the desktop
    guard let screen = NSScreen.screens.first else {
        print("Failed to retrieve screen")
        return nil
    }
    
    // Get the desktop image URL
    if let desktopImageURL = NSWorkspace.shared.desktopImageURL(for: screen) {
        // Extract and return the path from the URL
        return desktopImageURL.path
    } else {
        print("Failed to retrieve desktop wallpaper URL")
        return nil
     }
  }

  func handleWallpaperChange(newPath: String) {
    if let lastWallpaperPath = lastWallpaperPath, newPath != lastWallpaperPath {
        print("Desktop wallpaper changed!")
        // Handle the wallpaper change here
    }
    
    lastWallpaperPath = newPath
   }
  }
Summons answered 9/2 at 6:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.