Reputation: 5955
I trigger a js from a WKWebView and get the result in the block function. In the block function, I got the correct data. However, when I assign this data to the external variable outside, I always get nil value.
- (id)triggerJS:(NSString*)js { NSLog(@"JS = %@",js); __block id resultJS = nil; [self.webView evaluateJavaScript:js completionHandler: ^(id data, NSError* err) { resultJS = [data copy]; } ]; if (resultJS != nil) { NSString* str = (NSString*)resultJS; NSLog(@"Result of JS = %@", str); } else { NSLog(@"Result of JS = nil"); } return resultJS; }
Why is that? Thanks.
Upvotes: 0
Views: 244
Reputation: 1624
That is because the function evaluateJavaScript
is executed asynchronous way, so when you execute the if (resultJS != nil)
the "completionHandler
" is not executed yet, thats the reason that you always get nil
value.
The best improvement for this, is trying to re-write and adapt your code inside the "completionHandler
" block, that will manage the resultJS data.
Upvotes: 1