Search code examples
iosuinavigationcontrollerobjective-c-blocks

UINavigationController taking time to push ViewController


Take the following code:

[[[Resource alloc] init] get:@"/api/v1/basic_user/40/" params:nil completion:^(NSURLResponse *response, NSDictionary *data, NSError *connectionError) {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
    HomeViewController *homeView = [storyboard instantiateViewControllerWithIdentifier:@"HomeViewController"];

    NSLog(@"pushing...");
    [self.navigationController pushViewController:homeView animated:YES];
}];

This prints "pushing" and after about 10(not precisely) seconds my HomeViewController appears. The initWithCoder(the ViewController is instantiated from the Storyboard) has absolutely nothing. And that gets called just right after I push my VC.

But my viewDidLoad method is taking seconds to load. I can't tell how many seconds because it's not exact. It sometimes doesn't load at all! (e.g. my HomeViewController does not show up.

Here's the trickier part. If I move my push method outside my block everything works like a charm.

What's going on? Why is my VC so slow when inside the block?

EDIT:

The only thing that uses thread when the method in my resource is called is the code below:

[NSURLConnection sendAsynchronousRequest:_request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
    NSLog(@"%@", [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil] description]);
    [self toggleNetworkActivityIndicator];

    _lastResponse = response;
    success(response, data, connectionError);
}];

Solution

  • The only thing I can think of is whatever your doing in your resources method is on another thread through dispatch. So try wrapping your push view controller in a grand central dispatch back to the main queue like the following code:

    dispatch_async(dispatch_get_main_queue(), ^{
        // Push view controller here
    }); 
    

    This has solved some issues were when I was performing animations it would take 5-10 seconds to do something that usually only took about a half a second. Hope this helps.