iOS中JS与OC数据交互总结

2017-03-16  本文已影响1777人  Alphts

iOS开发过程中会经常和UIWebView打交道,这其中不可避免的涉及到JS和OC的数据交互,今天在此总结下这其中的几种方法.

OC调用JS的方法

但是这个方法是一个同步的方法,使用它执行JS方法时,如果JS 方法比较耗的时候,会造成界面卡顿.此时,将耗时较长的js方法放到setTimeout中即可.当然,如果尝试在子线程中调用stringByEvaluatingJavaScriptFromString显然是不正确的.报错信息如下:

Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...

JS调用OC的方法

但是html文件中的test()采用的window.location方式在多次请求时会存在被替换覆盖的问题,故采用下面这种方式:
<script>
function loadURL(url) {
var tempElement;
tempElement = document.createElement("tempElement");
tempElement.setAttribute("src", url);
tempElement.setAttribute("style", "display:none;");
tempElement.setAttribute("height", "0px");
tempElement.setAttribute("width", "0px");
tempElement.setAttribute("frameborder", "0");
document.body.appendChild(tempElement);
// 发起请求后这个 tempElement 就没用了,所以把它从 dom 上移除掉
tempElement.parentNode.removeChild(tempElement);
tempElement = null;
}
function test() {
var mydiv = document.getElementById("mydiv");
loadURL("bridge://" + mydiv.innerHTML);
}
</script>

上一篇 下一篇

猜你喜欢

热点阅读