React Native Error: must be used from main thread only
Question
In iOS, I use Objective C to create my own native module.
RCT_EXPORT_METHOD(startPay:(NSString*)tn :(NSString*)mode)
{
UIWindow *window = [UIApplication sharedApplication].keyWindow;
UIViewController *rootViewController = window.rootViewController;
[[UPPaymentControl defaultControl] startPay:tn
fromScheme:@"UPPayDemo" mode:mode
viewController:rootViewController];
}
When calling this method in Javascript module, Xcode made an error that it must be used from main thread only.
-[UIApplication keyWindow] must be used from main thread only
-[UIWindow rootViewController] must be used from main thread only
Solution
Call it from the main thread using dispatch_async(dispatch_get_main_queue(), ^{})
.
RCT_EXPORT_METHOD(startPay:(NSString*)tn :(NSString*)mode)
{
dispatch_async(dispatch_get_main_queue(), ^(void) {
UIWindow *window = [UIApplication sharedApplication].keyWindow;
UIViewController *rootViewController = window.rootViewController;
[[UPPaymentControl defaultControl] startPay:tn
fromScheme:@"UPPayDemo" mode:mode
viewController:rootViewController];
});
}