桌面壁纸更改时通知?

问题描述 投票:0回答:2

更改桌面壁纸时有任何通知吗?

谢谢!

cocoa macos notifications wallpaper
2个回答
2
投票
[[NSDistributedNotificationCenter defaultCenter] addObserver:target
    selector:@selector(desktopImageChanged:)
    name:@"com.apple.desktop"
    object:@"BackgroundChanged"];

应该去工作


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
   }
  }
© www.soinside.com 2019 - 2024. All rights reserved.