Last active
May 23, 2018 22:28
-
-
Save mminer/9e48cfbd2754610cff0fbe424c5b8717 to your computer and use it in GitHub Desktop.
Saves screenshots in a Cocoa application (wrapper around screencapture).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import AppKit | |
struct ScreenshotManager { | |
/// Matches macOS' screenshot filename format. | |
private static let filenameFormatter: DateFormatter = { | |
let formatter = DateFormatter() | |
formatter.dateFormat = "'Screen Shot' yyyy-MM-dd 'at' HH.mm.ss" | |
return formatter | |
}() | |
/// The paths to save the screenshot(s) at. | |
private static var paths: [String] { | |
let date = Date() | |
let filename = filenameFormatter.string(from: date) | |
return (1...NSScreen.screens.count).map { screenNumber -> String in | |
let suffix = screenNumber > 1 ? " (\(screenNumber))" : "" | |
return "/tmp/\(filename)\(suffix).png" | |
} | |
} | |
/// Takes and saves screenshots of the user's displays. | |
static func capture(completionHandler: @escaping ([String]) -> Void) { | |
let outputPaths = paths | |
let process = Process() | |
process.launchPath = "/usr/sbin/screencapture" | |
process.arguments = ["-x"] + outputPaths | |
process.standardOutput = Pipe() | |
process.terminationHandler = { task in | |
guard task.terminationStatus == 0 else { | |
return | |
} | |
completionHandler(outputPaths) | |
} | |
process.launch() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment