Search code examples
objective-cmultithreadinguiwebviewobjective-c-blocksnsinvocation

How to perform UIKit call on mainthread from inside a block


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.


Solution

  • 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
    });