无法使用SnapshotViewAfterScreenUpdate:UIScreen方法在iOS上获取屏幕截图

无法使用SnapshotViewAfterScreenUpdate:UIScreen方法在iOS上获取屏幕截图,ios,swift,screenshot,uiscreen,Ios,Swift,Screenshot,Uiscreen,我正在尝试在我的iOS应用程序中获取屏幕截图图像。屏幕截图必须包含屏幕上的所有内容,包括状态栏,因此解决方案(如)对我不起作用。我尝试了以下方法: override func viewDidLoad() { super.viewDidLoad() // Wait for one second before taking the screenshot. Timer.scheduledTimer(withTimeInterval: 1, repeats: false) {

我正在尝试在我的iOS应用程序中获取屏幕截图图像。屏幕截图必须包含屏幕上的所有内容,包括状态栏,因此解决方案(如)对我不起作用。我尝试了以下方法:

override func viewDidLoad() {
    super.viewDidLoad()

    // Wait for one second before taking the screenshot.
    Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { timer in
        // Get a view containing the screenshot, shrink it a little, and show it.
        let view = UIScreen.main.snapshotView(afterScreenUpdates: false)
        view.frame = view.frame.insetBy(dx: 18, dy: 32)
        self.view.addSubview(view)

        // Get the screenshot image from the view, and save it to the photos album.
        UIGraphicsBeginImageContextWithOptions(UIScreen.main.bounds.size, false, 0)
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
    }
}
我在iPhone6plus上的iOS 11.4.1中运行了上述代码。屏幕截图已成功捕获并显示在屏幕上,但保存到相册中的图像完全为空白。我做错了什么?捕获完整屏幕截图的正确方法是什么

更新 根据CZ54的建议,我在调试会话中检查了变量
image
的值,发现它是完全空白的,尽管它的大小是正确的。所以这里的关键问题是,如何从
UIScreen.main.snapshotView()方法返回的屏幕截图视图中提取图像?

Swift 4.1.1

   let deadlineTime = DispatchTime.now() + .seconds(1)
    // Wait for one second before taking the screenshot.
    DispatchQueue.main.asyncAfter(deadline: deadlineTime) {

        let view = UIScreen.main.snapshotView(afterScreenUpdates: false)
        view.frame = view.frame.insetBy(dx: 18, dy: 32)
        self.view.addSubview(view)

        // Get a view containing the screenshot, shrink it a little, and show it.
        UIGraphicsBeginImageContextWithOptions(self.view.frame.size, true, UIScreen.main.scale)
        //guard let context = UIGraphicsGetCurrentContext() else { return }
        //self.view.layer.render(in: context)
        self.view?.drawHierarchy(in:  self.view.bounds, afterScreenUpdates: true)
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return }
        UIGraphicsEndImageContext()

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

添加断点,检查您的图像之前saving@CZ54:我试过了,发现图像大小正确,确实是空白的。请将计时器替换为let deadlineTime=DispatchTime.now()+.seconds(1)DispatchQueue.main.asyncAfter(截止日期:deadlineTime){}谢谢您的回答。不幸的是,尽管
self.view?.drawHierarchy()
确实生成了一个映像,但此方法对我不起作用,因为生成的映像不包含状态栏。这就是为什么我需要调用
UIScreen.main.snapshotView()
,因为它生成的屏幕截图视图包含状态栏。这里的关键问题是如何从截图视图中提取图像。