Sync JavaScript in WKWebView

Create sync version

UIWebView javascript method is sync type.
On the other hand, WKWebView evaluateJavaScript:completionHandler: is async type.
Actually, we can get the result from callback method.
But, sometimes need sync type, waiting UI etc…

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)javascript {
     __block NSString *res = nil;
     __block BOOL finish = NO;
     [self evaluateJavaScript:javascript completionHandler:^(NSString *result, NSError *error){
         res = result;
         finish = YES;
     }];
     
     while (!finish) {
         [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
     }
     return res;
}

?
 

你可能感兴趣的:(iOS开发技术系列专栏)