2

My application renders a UIView to a UIImage using the below code:

func asImage() -> UIImage {
    let renderer = UIGraphicsImageRenderer(bounds: bounds)
    return renderer.image { rendererContext in
        self.drawHierarchy(in: bounds, afterScreenUpdates: true)
    }
}

Before that code gets called, I put a loading indicator on screen that should display while the image rendering is in-progress. That indicator is an animated sequence via a UIImageView. The loading animation starts fine, but as soon as the image rendering starts, the main thread is blocked and the loading animation freezes. It hangs until the rendering in complete and then resumes. I believe both the UIImageView manipulation as well as the rendering has to happen on the main thread so I'm not sure how I can avoid the animation from freezing during this process. Thoughts?

  • Looking at https://stackoverflow.com/questions/6348962/safe-way-to-render-uiview-to-an-image-on-background-thread and similar, I’d say there’s nothing you can do. Taking a snapshot view is faster. But everything has to happen on the main thread as far as I can tell. – matt Mar 20 '20 at 20:35
  • You can absolutely do the rendering logic in the background. As long as you are not actually displaying it on the screen yet, you don't have to be on the main thread. See https://stackoverflow.com/questions/22338727/drawing-in-the-background – AnthonyMDev Mar 20 '20 at 20:44
  • @AnthonyMDev appreciate the response. Tried the approach in that post but am getting "'NSInternalInconsistencyException', reason: 'threading violation: expected the main thread'" and Xcode is calling out the UIGraphicsImageRenderer and drawHierarchy calls directly as "must be used from main thread only" :/ – TheCodeBender Mar 20 '20 at 21:08
  • Did you ever fix this? – Tometoyou Sep 24 '22 at 17:38

0 Answers0