Search code examples
iosswiftxcodescreenshot

Taking screenshot using Swift 5 returns a black image and not the app's screen


I'm trying to take a screenshot of my app and then share it.

The problem I'm having is that when I take a screenshot and save it to the Photos app, the image that gets saved is completely black (and not the screenshot of my app).

How can I get the screenshot to be of my app? What am I missing?

func takeScreenshot() {
        let bounds = UIScreen.main.bounds
        UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
        self.view.drawHierarchy(in: bounds, afterScreenUpdates: false)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        let activityViewController = UIActivityViewController(activityItems: [img!], applicationActivities: nil)
        self.present(activityViewController, animated: true, completion: nil)
    }

App is a single screen.
Swift 5
xCode 10

I've tried browsing other similar StackOverflow issues and tweaking my code to theirs but getting the same results. Hitting a wall and trying here.

Thanks for any help!

View Controller Scene


Solution

  • Try changing

     afterScreenUpdates: false
    

    To

     afterScreenUpdates: true
    

    That way there will be some drawing to snapshot.