BenL0
BenL0

Reputation: 287

Notification when desktop wallpaper changes?

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

Thanks!

Upvotes: 6

Views: 747

Answers (2)

Mannam Brahmaiah
Mannam Brahmaiah

Reputation: 2283

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
   }
  }

Upvotes: 0

Stefanf
Stefanf

Reputation: 1693

[[NSDistributedNotificationCenter defaultCenter] addObserver:target
    selector:@selector(desktopImageChanged:)
    name:@"com.apple.desktop"
    object:@"BackgroundChanged"];

should to the job

Upvotes: 2

Related Questions