Search code examples
iosswiftscreenshotuialertview

Screenshot of an alert, iOS, Swift


I am taking a screenshot when I show an alert, this works in taking a screenshot but when it is saved to the camera roll it has only captured the screen behind the alert and hasn't included the alert in the screenshot.

Is it possible to do this?

Below is my code.

func ScreenShot() {
    //Create the UIImage
    UIGraphicsBeginImageContextWithOptions(view.frame.size, true, 0)
    guard let context = UIGraphicsGetCurrentContext() else { return }
    view.layer.render(in: context)
    guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return }
    UIGraphicsEndImageContext()

    //Save it to the camera roll
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

caling it here.

func alertShow() {

    let alert = UIAlertController(title: "ALERT!!!", message: "Message stuff", preferredStyle: UIAlertControllerStyle.alert)


    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { action in

        self.performSegue(withIdentifier: "toMainInfoVC", sender: nil)

    }))

    self.present(alert, animated: true, completion: nil)
    ScreenShot()
}

Solution

  • I think you need the complete layer of the key window

    let layer = UIApplication.shared.keyWindow!.layer
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
    
    layer.render(in: UIGraphicsGetCurrentContext()!)