Search code examples
iosswiftuigraphicscontext

drawHierarchy fails when afterScreenUpdates: true


I am using the following code to grab a screenshot of my view.

UIGraphicsBeginImageContext(self.view.bounds.size)
self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: true)
let wholeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

If I set "afterScreenUpdates:" to false, it works correctly. But if I set it to true, I get the following error:

*** Assertion failure in -[UIApplication _performWithUICACommitStateSnapshotting:](), /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3600.5.2/UIApplication.m:6882

Using breakpoints, I found that the error throws on the drawHierarchy method. Anyone seen this error before? Any idea what's going on? I've tried taking out any updates to the view (hiding some uiimages) before grabbing the snapshot, but it has no effect.

Strange side note: the app freezes with this error, but there's no hard stop (I can't interact with the debugger to look at the backtrace). Sorry if that's unclear.


Solution

  • I got this error as well. The issue is that all UIKit work in iOS needs to be done on the main thread. A quick solution is to wrap it in a DispatchQueue.async call from the main thread:

    var wholeImage : UIImage?
    
    DispatchQueue.main.async {
        UIGraphicsBeginImageContext(self.view.bounds.size)
        self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: true)
        self.wholeImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    }