skip to Main Content
extension UIViewController {
    
    static func takeScreenshot() -> UIImage? {
        
        guard let topController = UIApplication.getTopController() else { return nil }
        
        if let view = topController.view {
            
            UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale)
            
            defer { UIGraphicsEndImageContext() }
            
            if let context = UIGraphicsGetCurrentContext() {
                
                view.layer.render(in: context)
                let screenshot = UIGraphicsGetImageFromCurrentImageContext()
                return screenshot
            }
        }
        return nil
    }
}

This code works perfectly, but the issue is when we have UIAlertController on top, I want to take screenshot of the entire screen (not the status bar of course) but the controller as well as any alert controller that is presented on top. Right now the code is working fine if there is no alert controller on top.

2

Answers


  1. Here’s the function that might help

    func captureScreenshot() -> UIImage? {
        // Ensure you have a reference to the main window
        guard let window = UIApplication.shared.windows.first else {
            return nil
        }
        
        // Begin drawing the context
        UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, 0.0)
        
        // Render the contents of the window's layer into the context
        window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
        
        // Get the image from the context
        let screenshotImage = UIGraphicsGetImageFromCurrentImageContext()
        
        // End drawing the context
        UIGraphicsEndImageContext()
        
        return screenshotImage
    }
    
    Login or Signup to reply.
  2. The code you are using will only take a screenshot of the top-most view controller and not the elements display on top of it.

    You could instead look into taking a snapshot of the key window:

    let keyWindow = UIWindowScene().keyWindow!
    let layer = keyWindow.layer
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
    ...//rest of your code 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search