0

I wrote a NativeX Phonegap/Cordova plugin. Now I'm trying to push the fetchAdWithCustomPlacement call into a background thread to avoid blocking the main thread.

NSString* adName = [command.arguments objectAtIndex:0];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [[NativeXSDK sharedInstance] fetchAdWithCustomPlacement:adName delegate:self];
});

Nothing errors, and the dispatch_async block is definitely run, but the corresponding NativeX callback never fires, as it does if I fetch the ad in the main thread. Callback:

- (void)nativeXAdView:(NativeXAdView *)adView didLoadWithPlacement:(NSString *)placement

First time using GCD. Don't know if I'm doing something wrong or if its the NativeX library. They distribute is a static library so I haven't read the source.

Any help is appreciated!

Dan
  • 641
  • 9
  • 25

1 Answers1

1

The NativeX iOS SDK should be run on the main UI thread for a couple reasons.

First, the SDK uses NSURLConnection to make the ad requests from the server; this is already an async operation, and doesn't need to be done from a background thread. By Apple's suggestion, NSURLConnection shouldn't be done in a background thread:

NSURLConnection and grand central dispatch

GCD and async NSURLConnection

With the GCD thread that is created, the thread won't have a runloop long enough for the SDK to receive the NSURLConnection delegate calls when it finishes.

You can extend the GCD thread runloop to run into the distant future, but this causes another issue with the NativeX SDK; when the connection finishes the SDK preloads the ad by creating a UIWebView. That UIWebView can only be created on the main thread; creating it on a background thread causes UIKit to crash.

In short; you should be calling the NativeX SDK from the main thread only.

Community
  • 1
  • 1
cyrix
  • 308
  • 2
  • 7