snapshotView(afterScreenUpdates:true) returns empty view when run on real device

Viewed 1014

When running in simulator (iPhone 7 and iPhone XR) snapshotView(afterScreenUpdates: true) works great and as expected. However when I test it on my physical iPhone 7 device it returns a blank view but with the correct frame

I need the UIView object and cannot use a UIImage as many of the previous answers to similar questions suggest.

let snappedView = view.snapshotView(afterScreenUpdates: true)
2 Answers

Maybe this extension will work for you:

public extension UIView {

    public func snapshotImage() -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
        drawHierarchy(in: bounds, afterScreenUpdates: false)
        let snapshotImage =         UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return snapshotImage
    }

    public func snapshotView() -> UIView? {
        if let snapshotImage = snapshotImage() {
            return UIImageView(image: snapshotImage)
        } else {
            return nil
        }
    }
}

You may use this function to take a screenshot of your iPhone screen, if that's what you need:

func takeSnapshot() {
  UIGraphicsBeginImageContext(view.frame.size)
  view.layer.render(in: UIGraphicsGetCurrentContext()!)
  let img = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()
}
Related