How can i wait for 2 seperate UIGraphicsImageRenderer tasks to complete

I have 2 UIGraphicsImageRenderer tasks with different renderers and when i run this, only one task is returned as it is synchronous, how do I wait until both have created images before returning them?

func createShareImage(callback: @escaping (_ image: UIImage, _ bgImage: UIImage) -> Void) {

    let canvas = UIView()
    ...

    let format = UIGraphicsImageRendererFormat()
    format.scale = UIScreen.main.scale

    let renderer = UIGraphicsImageRenderer(size: canvas.bounds.size, format: format)
    let stickerImage = renderer.image { _ in
        canvas.drawHierarchy(in: canvas.bounds, afterScreenUpdates: true)
    }

    let bgImageView = UIView()
    ...

    let bgRenderer = UIGraphicsImageRenderer(size: bgImageView.bounds.size, format: format)
    let bgImage = bgRenderer.image { _ in
        bgImageView.drawHierarchy(in: bgImageView.bounds, afterScreenUpdates: true)
    }

    callback(stickerImage, bgImage)
    
}

1 answer

  • answered 2022-01-25 14:17 Sh_Khan

    Testing your code

    func createShareImage(callback: @escaping (_ image: UIImage, _ bgImage: UIImage) -> Void) {
    
        let canvas = UIView(frame: CGRect.init(x: 0, y: 0, width: 200, height: 200))
        canvas.backgroundColor = .red
        let format = UIGraphicsImageRendererFormat()
        format.scale = UIScreen.main.scale
        print("1:",Thread.isMainThread)
        let renderer = UIGraphicsImageRenderer(size: canvas.bounds.size, format: format)
        let stickerImage = renderer.image { _ in
            canvas.drawHierarchy(in: canvas.bounds, afterScreenUpdates: true)
            print("2:",Thread.isMainThread)
        }
    
        let bgImageView = UIView(frame: CGRect.init(x: 0, y: 0, width: 2000, height: 2000))
        bgImageView.backgroundColor = .green
        let bgRenderer = UIGraphicsImageRenderer(size: bgImageView.bounds.size, format: format)
        let bgImage = bgRenderer.image { _ in
            bgImageView.drawHierarchy(in: bgImageView.bounds, afterScreenUpdates: true)
            print("3:",Thread.isMainThread)
        }
    
        print("4:",Thread.isMainThread)
        callback(stickerImage, bgImage)
    }
    

    Gets

    1: true
    2: true
    3: true
    4: true
    

    Which means there is no async part , all the code is synchronous and serial and no waiting need to happen

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum