0

I´ve question regarding parallel processing of an image with an loading overlay. I´m processing an image in a function which needs some seconds. During that time a loading overlay should be shown.

The problem is, that the loading overlay appears AFTER the image is processed although it´s called BEFORE the image is processed.

@IBAction func onFilterRed(sender: UIButton) {

    LoadingOverlay.shared.showOverlay(self.view)

    var rgbaImage = RGBAImage(image: self.originalImage!)
    rgbaImage?.adjustColor(red: 80, green: -30, blue: -30)

    self.filteredImage = rgbaImage?.toUIImage()
    imageView.image = self.filteredImage


}

I´ve no idea why the overlay isn´t shown at the point where it´s called.

Thanks for any hint, Michael

Michael
  • 2,966
  • 3
  • 30
  • 33

1 Answers1

1

From what I can see, you are operating only on main thread: that's why the UI is blocked while the image is processing. The display update doesn't happen in the exact moment you call your code: it gets queued with all the other UI-update code, so they will run all together once per runloop. You can see an explanation here: Order of operations in runloop on iOS.

Anyway, you could solve like this:

@IBAction func onFilterRed(sender: UIButton) {
    LoadingOverlay.shared.showOverlay(self.view)

    // Run on a background thread
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        var rgbaImage = RGBAImage(image: self.originalImage!)
        rgbaImage?.adjustColor(red: 80, green: -30, blue: -30)

        self.filteredImage = rgbaImage?.toUIImage()

        // Run again on main thread (UI updating code MUST run on main thread)
        dispatch_async(dispatch_get_main_queue()) {
            imageView.image = self.filteredImage
        }
    }
}
Community
  • 1
  • 1
Alessandro Orrù
  • 3,443
  • 20
  • 24