目前ios已经不让用uiwebview了,所以WebViewJavascriptBridge也不推荐使用了,原生调H5其实很简单,本质就是调用JS而已,给你参考下我的做法吧
[Objective-C] 纯文本查看 复制代码
#pragma mark - JS 交互
- (void)JSInvoke:(NSString *)function params:(NSDictionary *)params callback:(void (^)(NSDictionary *result, NSDictionary *params))callback {
NSString *paramsStr = params ? [params yy_modelToJSONString] : @"null";
if (!callback) {
return [self runJS:[NSString stringWithFormat:@"%@(%@)", function, paramsStr] callback:nil];
}
WKWebView *webview = self.webViews[[self currentWindow]];
if (webview) {
NSString *token = [[NSUUID UUID] UUIDString];
NSString *code = [NSString stringWithFormat:@"JSInvokeFinished('%@',%@(%@),%@);", token, function, paramsStr, paramsStr];
self.callbacks[token] = [callback copy];
dispatch_async(dispatch_get_main_queue(), ^{
[webview evaluateJavaScript:code completionHandler:^(id _Nullable result, NSError * _Nullable error) {
if (error) {
NSLog(@"异常发生%@", error);
}
}];
});
}
}
- (void)runJS:(NSString *)code on:(NSString *)token callback:(void(^)(NSDictionary *result, NSDictionary *params))callback {
if (!token) {
token = [self currentWindow];
}
WKWebView *webview = self.webViews[token];
if (webview) {
NSString *token = [[NSUUID UUID] UUIDString];
if (callback) {
self.callbacks[token] = [callback copy];
code = [NSString stringWithFormat:@"%@;JSInvokeFinished('%@');", code, token];
}
dispatch_async(dispatch_get_main_queue(), ^{
[webview evaluateJavaScript:code completionHandler:^(id _Nullable result, NSError * _Nullable error) {
if (error) {
NSLog(@"异常发生%@", error);
}
}];
});
}
}
- (void)runJS:(NSString *)code callback:(void(^)(NSDictionary *result, NSDictionary *params))callback {
return [self runJS:code on:[self currentWindow] callback:callback];
}
|