2

I am trying to push a view controller from inside a callback block. The view controller I want to push contains a UIWebView, which complains that I should call this on the main thread. I tried using NSInvocation to no avail. How can I call presentModalViewController:animated on the main thread?

[vc requestUserPermissionWithCallback:^(BOOL inGranted)
         {
             if (inGranted)
             {
                 if (serviceType == PXServiceTypeTwitter)
                 {
                     //[ad.rootViewController presentModalViewController:vc animated: YES]; // crashes
                     NSInvocation *invocation = [NSInvocation invocationWithTarget:ad.rootViewController selector:@selector(presentModalViewController:animated:) retainArguments:YES, vc, YES];
                     [invocation invokeOnMainThreadWaitUntilDone:NO]; // same result
                 }
             }
             else
             {
                 [self.navigationController popToRootViewControllerAnimated:YES];
             }
         }];

error message:

bool _WebTryThreadLock(bool), 0x6b21090: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...

I am using the category NSInvocation+CWVariableArguments.

Monolo
  • 18,205
  • 17
  • 69
  • 103
Morrowless
  • 6,856
  • 11
  • 51
  • 81

2 Answers2

8

Just use dispatch_get_main_queue() to get the main thread and then dispatch to it:

dispatch_async(dispatch_get_main_queue(), ^{
    // whatever code you want to run on the main thread
});
yuji
  • 16,695
  • 4
  • 63
  • 64
0

I had a similar issue and used

performSelectorOnMainThread:withObject:waitUntilDone:

to solve it. Hope that helps.

mgauthier
  • 321
  • 2
  • 6