Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

Programmatically Screenshot | Swift 3, macOS

Is it possible to take a screenshot programmatically of the desktop on mac using Swift 3? I can't find a single thread or forum post about the topic, not even in apple's official documentation.

I have found this so far but it doesn't seem to help: one two

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes its possible. This function takes all connected monitors screenshots and writes to specified path as jpg file. Generates file name as unix time stamp.

 func TakeScreensShots(folderName: String){
    
    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: [:])!
        
        
        do {
            try jpegData.write(to: fileUrl, options: .atomic)
        }
        catch {print("error: (error)")}
    }
}

func CreateTimeStamp() -> Int32
{
    return Int32(Date().timeIntervalSince1970)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...