Search code examples
swiftscreenshotmacos-catalina

CGDisplayCreateImage takes only wallpapers screenshot


enter image description here

I want to take a screenshot of Mac OS X, but I am getting only wallpaper image.

What did I miss? I am using Mac-Catalina.

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: folderName + "\(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: [:])!
    
    let fileManager = FileManager.default
    
   
    do {

        let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
        let fileURL = documentDirectory.appendingPathComponent("\(unixTimestamp)" + "_" + "\(i)" + ".jpg")
       
            try jpegData.write(to: fileURL)
            
       
    } catch {
       print(error)
    }

Solution

  • You make a screenshot using external Process /usr/sbin/screencapture

    Just provide -r parameters. Launching external process is quite expensive operation, perhaps there is a way to do it w/o launching the process.

    /usr/sbin/screencapture -r "1.png" (just remove "-i" )

    Check Screen Capture SDK