Observe user screen shot event and image in macOS.
let observer = ScreenShotObserver()
observer.delegate = self
observer.start()func screenShotObserver(_ observer: ScreenShotObserver, addedItem item: NSMetadataItem) {
print("added item == \(item)")
}
func screenShotObserver(_ observer: ScreenShotObserver, updatedItem item: NSMetadataItem) {
print("updated item == \(item)")
}
func screenShotObserver(_ observer: ScreenShotObserver, removedItem item: NSMetadataItem) {
print("removed item == \(item)")
}Change observing status
observer.isEnabled = false // Stop observing
observer.isEnabled = true // Restart observingSecurity features have been enhanced since mac10.15 Catalina, and screenshot monitoring must be granted permission. The monitoring target can be specified for each directory. By default, Screeen monitors the user's custom macOS screenshot save location (com.apple.screencapture → location) as well as the Desktop. If no custom location is configured, it monitors the Desktop only.
When call start() for the first time, a permission alert will be displayed and monitoring will start when allow it.
let observer = ScreenShotObserver()
observer.start()
The screenshot save location is read when the observer is initialized. Create a new observer to pick up a changed location. Paths beginning with ~ are expanded, and duplicate directories are monitored only once.
Passing searchDirectoryPaths explicitly overrides these defaults; the custom screenshot save location and Desktop are not added to the supplied paths.
let desktopPath = NSSearchPathForDirectoriesInDomains(.desktopDirectory, .userDomainMask, true).first
let picturePath = NSSearchPathForDirectoriesInDomains(.picturesDirectory, .userDomainMask, true).first
let directoryPaths = [desktopPath, picturePath].compactMap { $0 }
let observer = ScreenShotObserver(searchDirectoryPaths: directoryPaths)
observer.start()
let observer: ScreenShotObserver
if #available(macOS 10.15, *) {
observer = ScreenShotObserver()
} else {
observer = ScreenShotObserver(searchDirectoryPaths: [])
}
observer.start()
In order to monitor screen shots in a Sandbox enabled application, the user must manually select the directory to be monitored.
See here for more details on how to implement it.