Show activity indicator when loading ViewController

I have a ViewController that takes time to load my views. When I launch the Tools, I see on the main screen if I click on the icon that pushes this view controller onto the stack, laying out the views halfway and getting the data for the views. I tried to add an activity indicator that will be displayed on the main screen above the button when the button is clicked to push the LongRunningViewController onto the stack. So I basically do this:

- (IBAction)puzzleView:(id)sender { dispatch_async(dispatch_get_main_queue(), ^{ [self.activityIndicator startAnimating]; }); PuzzleViewController *detailViewController = [[[PuzzleViewController alloc] init] autorelease]; [self.navigationController pushViewController:detailViewController animated:YES]; [self.activityIndicator stopAnimating]; } 

The main screen is paused by pressing a button and then loading the view. I'm trying to show an activity indicator while another screen is getting ready to be pressed (or at least the way I think it works). However, the activity indicator is not displayed. I am wondering if this can be done? Or do other applications click on their ViewController, and then on this screen do they have activity indicators showing the loading of their various resources?

+4
source share
1 answer

When you say it takes time to get the data for the views, I assume that you mean that the PuzzleViewController doing something non-trivial somewhere like viewDidLoad .

So let's say it is in viewDidLoad . Then you can do this:

 -(void)viewDidLoad { [self.activityIndicator startAnimating]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ { //do something expensive [self doSomethingExpensive]; //dispatch back to the main (UI) thread to stop the activity indicator dispatch_async(dispatch_get_main_queue(), ^ { [self.activityIndicator stopAnimating]; }); }); } 

This will mean that an expensive operation will be placed in the background thread and will not block the loading / display of the view controller.

This approach immediately displays the requested view when the user presses a button and shows the progress on this screen. I believe this is more common than showing an activity view when loading content before presenting the view. It also buys you a little more time; Your long operation can run in the background during the transition animation!

The reason your activity doesn't show how you do it is because you are doing all this in the user interface thread; using dispatch_async in the main queue from the main queue will not do anything, because your block will not work until the loop cycle completes.

+9
source

Source: https://habr.com/ru/post/1436014/


All Articles