NSURL* htmlURL = [[NSBundle mainBundle] URLForResource: @"demo" withExtension: @"html"]; [_webView loadRequest: [NSURLRequest requestWithURL: htmlURL]];
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function showAlert(){
alert('OC call JS with no argument');
}
function showAlertWithString(string){
alert(string);
}
function callOCWithArgument() {
jsCallOCWithArgument('参数1 ','参数2 ','参数3');
}
</script>
</head>
<body>
</br>
</br>
</br>
</br>
<form>
<button type='button' onclick='callOC()'>jsCallOC</button>
<button type='button' onclick='callOCWithArgument()'>jsCallOCWithArgument</button>
</form>
</body>
</html>
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
_context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
__weak typeof(self) weakSelf = self;
_context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
weakSelf.context.exception = exception;
};
//js调用OC
_context[@"callOC"] = ^() {
NSArray *args = [JSContext currentArguments];
for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal.toString);
}
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"arguments" message:@"JS Call OC With No Argument" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * action = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}];
[alertView addAction:action];
[weakSelf presentViewController:alertView animated:YES completion:nil];
});
};
_context[@"jsCallOCWithArgument"] = ^() {
NSArray *args = [JSContext currentArguments];
NSMutableString * stirng = [NSMutableString string];
for (JSValue * value in args) {
[stirng appendString:value.toString];
}
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"arguments" message:stirng preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * action = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}];
[alertView addAction:action];
[weakSelf presentViewController:alertView animated:YES completion:nil];
});
};
}
- (IBAction)callJS:(id)sender {
[_context evaluateScript:@"showAlert()"];
}
- (IBAction)callJSWithArguments:(id)sender {
[_context evaluateScript:@"showAlertWithString('OC call JS with arguments')"];
// [_context[@"showAlertWithString"] callWithArguments:@[@"OC call JS with arguments"]];
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有