Reputation: 65
I want to take a snapshot from view including the status bar.
the code below works in the simulator but doesn't on a physical device.
extension UIScreen {
class func screenshot() -> UIImage {
let view = main.snapshotView(afterScreenUpdates: false)
UIGraphicsBeginImageContext(view.bounds.size)
view.drawHierarchy(in: view, afterScreenUpdates: true)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return screenshot!
}
}
Upvotes: 0
Views: 412
Reputation: 5689
Create a extension like:
extension UIApplication {
func getViewScreenShot(vc: UIViewController) -> UIImage? {
let scale = UIScreen.main.scale
let bounds = vc.view.bounds
UIGraphicsBeginImageContextWithOptions(bounds.size, false, scale)
if UIGraphicsGetCurrentContext() != nil {
vc.view.drawHierarchy(in: bounds, afterScreenUpdates: true)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return screenshot!
}
return nil
}
}
And call it like:
weak var weakSelf = self
let screenShotImage: UIImage = UIApplication.shared.getViewScreenShot(vc: weakSelf!)
Upvotes: 0
Reputation: 1137
to fix your problem you can use this function:
func takeScreenshot() -> 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()
return screenshotImage
}
I just tested this and it works on a physical device.
Upvotes: 1