Search code examples
iosswiftuialertcontrolleruiprogressview

ProgressView not showing on View Controller using Swift


I am showing an alertController and if the user clicks Yes an ProgressView should be shown, but unfortunately the Progressview and the label does not appear. How can I refresh my ViewController. Here the cod that is executed for the yes-handler of the alertController. The code will be executed without problem, but the progressview is not appearing:

func initProgressView(){
    turn = 0
    let xCoord = self.view.center.x
    let yCoord = self.view.center.y + 10
    progressLabel = UILabel(frame: CGRect(x: xCoord, y: yCoord, width: 100, height: 23))
    progressLabel.text = "0 %"



    progressLabel.font = UIFont.boldSystemFontOfSize(14)
    progressView.center = self.view.center
    progressView.trackTintColor = UIColor.lightGrayColor()
    progressView.tintColor = UIColor.blueColor()
   // self.view.backgroundColor = UIColor.yellowColor()
    self.view.addSubview(progressLabel)
    self.view.addSubview(progressView)

}

here the complete sequence of call: initProgressView() //see previous post

then call of importData:

func importData (source : ImportDataInterface, data : NSData, progressStep : Int) {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
            source.importData(data)
            dispatch_async(dispatch_get_main_queue(), {
                self.counter += progressStep
                return
            })
        })



}

and finally in the calling function: progressView.removeFromSuperview() progressLabel.removeFromSuperview()

How can I refresh the ViewController or what else could be the reason why the progressView does not appear. Can it be, that constraints or autolayout issues are the problem.

thanks Arnold


Solution

  • You haven't provided enough information. You need to show us the sequence of calls.

    iOS doesn't render changes to the screen until your code returns. The following coding pattern will not work:

    create progress indicator
    add progress indicator to superview
    start progress indicator spinning
    do long-running task
    stop progress indicator
    

    Instead, what you have to do is something like this:

    create progress indicator
    add progress indicator to superview
    start progress indicator spinning
    invoke long-running task with a call to dispatch_after and a delay of 0:
    dispatch_after(main queue, delay 0)
    {
       do long running task
       stop activity indicator
    }
    

    The call to dispatch_after queues up your closure to run on the main thread the next time your code returns and the event loop even if the delay value is 0.