I have created an Xcode swift based software that is menu based. One of the buttons I have created is intended to capture a screenshot and save the file to a specific location.
I have found sources explaining how to do this on iOS, but I'm looking for macOS functionality. The article: Programmatically Screenshot | Swift 3, macOS has responses that have gotten me close but I think some of it is deprecated.
How can I implement this in a software developed for macOS with Xcode & Swift 5.
Here is the code for the function:
@objc func TakeScreenshot(_ sender: Any){
func CreateTimeStamp() -> Int32
{
return Int32(Date().timeIntervalSince1970)
}
var displayCount: UInt32 = 0;
var result = CGGetActiveDisplayList(0, nil, &displayCount)
if (result != CGError.success) {
print("error: \(result)")
return
}
let allocated = Int(displayCount)
let activeDisplays = UnsafeMutablePointer<CGDirectDisplayID>.allocate(capacity: allocated)
result = CGGetActiveDisplayList(displayCount, activeDisplays, &displayCount)
if (result != CGError.success) {
print("error: \(result)")
return
}
for i in 1...displayCount {
let unixTimestamp = CreateTimeStamp()
let fileUrl = URL(fileURLWithPath: "~/Documents" + "\(unixTimestamp)" + "_" + "\(i)" + ".jpg", isDirectory: true)
let screenShot:CGImage = CGDisplayCreateImage(activeDisplays[Int(i-1)])!
let bitmapRep = NSBitmapImageRep(cgImage: screenShot)
let jpegData = bitmapRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
do {
try jpegData.write(to: fileUrl, options: .atomic)
}
catch {print("error: \(error)")}
}
}
menu.addItem(NSMenuItem(title: "Take Screenshot", action:
#selector(AppDelegate.TakeScreenshot(_:)), keyEquivalent: ""))
The second portion of code is the menu item that is a button. I want this button to take a screenshot of the screen and then save the file to a location I specify.
I get this error when I use the button on my application: Error