使用JavaScriptCore实现OC和JS交互详解
JavaScriptCore
JavaScriptCore是webkit的一个重要组成部分,主要是对JS进行解析和提供执行环境。iOS7后苹果在iPhone平台推出,极大的方便了我们对js的操作。
首先创建webView,读取本地的html文件
NSURL*htmlURL=[[NSBundlemainBundle]URLForResource:@"demo"withExtension:@"html"]; [_webViewloadRequest:[NSURLRequestrequestWithURL:htmlURL]];
在demo中,我们要实现4种情况
- JS调用OC
- JS调用OC并传递参数
- OC调用JS
- OC调用JS并传递参数
html文件中代码如下
functionshowAlert(){ alert('OCcallJSwithnoargument'); } functionshowAlertWithString(string){ alert(string); } functioncallOCWithArgument(){ jsCallOCWithArgument('参数1','参数2','参数3'); }
JS调用OC
在webView的代理方法webViewDidFinishLoad中
-(void)webViewDidFinishLoad:(UIWebView*)webView
{
_context=[webViewvalueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
__weaktypeof(self)weakSelf=self;
_context.exceptionHandler=^(JSContext*context,JSValue*exception){
weakSelf.context.exception=exception;
};
//js调用OC
_context[@"callOC"]=^(){
NSArray*args=[JSContextcurrentArguments];
for(JSValue*jsValinargs){
NSLog(@"%@",jsVal.toString);
}
dispatch_async(dispatch_get_main_queue(),^{
UIAlertController*alertView=[UIAlertControlleralertControllerWithTitle:@"arguments"message:@"JSCallOCWithNoArgument"preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction*action=[UIAlertActionactionWithTitle:@"Done"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction){
}];
[alertViewaddAction:action];
[weakSelfpresentViewController:alertViewanimated:YEScompletion:nil];
});
};
_context[@"jsCallOCWithArgument"]=^(){
NSArray*args=[JSContextcurrentArguments];
NSMutableString*stirng=[NSMutableStringstring];
for(JSValue*valueinargs){
[stirngappendString:value.toString];
}
dispatch_async(dispatch_get_main_queue(),^{
UIAlertController*alertView=[UIAlertControlleralertControllerWithTitle:@"arguments"message:stirngpreferredStyle:UIAlertControllerStyleAlert];
UIAlertAction*action=[UIAlertActionactionWithTitle:@"Done"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction){
}];
[alertViewaddAction:action];
[weakSelfpresentViewController:alertViewanimated:YEScompletion:nil];
});
};
}
我们定义一个block,然后保存到context里面,其实就是转换成了JS中命名为callOC的function。然后我们直接执行这个function,调用的就是我们的block里面的内容了。
传过来的参数可以通过[JSContextcurrentArguments]这个array接受,里面是JSValue对象。
OC调用JS
初始化两个Button,在点击事件中实现如下方法
-(IBAction)callJS:(id)sender{
[_contextevaluateScript:@"showAlert()"];
}
-(IBAction)callJSWithArguments:(id)sender{
[_contextevaluateScript:@"showAlertWithString('OCcallJSwitharguments')"];
//[_context[@"showAlertWithString"]callWithArguments:@[@"OCcallJSwitharguments"]];
}
即可实现OC调用JS。
demo已上传,需要的可以点此下载查看。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。