How to generate screenshot

I have been trying to use screenshot() documentation i have found is for testing purposes

I am not having any luck I have checked stackover-flow as well but seems to be for an older version of swift or just not functioning code as stackover -low sometimes is.


Has anyone had any success with screenshotting the view with UIIimage and saving it to the camera roll?

this is the closest I have got

keyWindow is deprecated in 13 but not relevant having an issue with line 7 as well not like the return of nill for some reason

 
/// - Returns: (Optional)image captured as a screenshot
 open func takeScreenshot(_ shouldSave: Bool = true) -> UIImage? {
  var screenshotImage :UIImage?
  let layer = UIApplication.shared.keyWindow!.layer
  let scale = UIScreen.main.scale
  UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
  guard let context = UIGraphicsGetCurrentContext() else {return nil}
  layer.render(in:context)
  screenshotImage = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()
  if let image = screenshotImage, shouldSave {
  UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
  }
  return screenshotImage
  }