Skip to content

Instantly share code, notes, and snippets.

@Ridwy
Created August 8, 2017 04:15
Show Gist options
  • Save Ridwy/7060bb9b96a38e01acc6aca75f622a36 to your computer and use it in GitHub Desktop.
Save Ridwy/7060bb9b96a38e01acc6aca75f622a36 to your computer and use it in GitHub Desktop.
take screenshots of each UIViewController
import UIKit
import AVFoundation
// call this in application(_:didFinishLaunchingWithOptions:)
func setupDebugScreenshot() {
let from = class_getInstanceMethod(UIViewController.self, #selector(UIViewController.viewDidAppear))
let to = class_getInstanceMethod(UIViewController.self, #selector(UIViewController.viewDidAppearWithScreenshot))
method_exchangeImplementations(from, to)
}
extension UIViewController {
func viewDidAppearWithScreenshot(_ animated: Bool) {
viewDidAppearWithScreenshot(animated)
guard let view = view, let _ = view.window, let name = NSStringFromClass(type(of: self)).components(separatedBy: ".").last else {
return
}
if name.hasPrefix("UI") {
return
}
AudioServicesPlaySystemSoundWithCompletion(SystemSoundID(1117), nil) // rec start sound
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
takeScreenshot(of: view, filename: name, directory: "ViewControllers")
AudioServicesPlaySystemSoundWithCompletion(SystemSoundID(1108), nil) // shutter sound
}
}
}
private func takeScreenshot(of view: UIView, filename: String, directory: String) {
// take screen shot
guard let window = view.window else {
return
}
let frame = view.convert(view.bounds, to: window)
if frame.isEmpty {
return
}
UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, UIScreen.main.scale)
window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(UIColor.red.cgColor)
context?.setLineWidth(4)
context?.stroke(frame)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// create directory if not exist
guard let documentDirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else {
return
}
let dirPath = (documentDirPath as NSString).appendingPathComponent(directory)
let fm = FileManager.default
if !fm.fileExists(atPath: dirPath) {
try? fm.createDirectory(atPath: dirPath, withIntermediateDirectories: true, attributes: nil)
}
// save
if let image = image, let data = UIImagePNGRepresentation(image) {
let savePath = (dirPath as NSString).appendingPathComponent(filename + ".png")
print(savePath)
let url = URL(fileURLWithPath: savePath)
try? data.write(to: url)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment