iOS 初探基于UIWebView的混编

2017-05-22  本文已影响17人  齐舞647

Objective-C 与 JavaScript 互相调用:


iOS的原生界面基于Objective-C语言,
UIWebView界面基于JavaScript语言。

问题:如何做OC和JS语言之间的跨语言相互调用?

设计图
Objective-C调用JavaScript:
//Objective-C:
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(nonnull NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSURL *url = [request URL];
    if ([[url scheme]isEqualToString:@"gap"]) {
        [webView stringByEvaluatingJavaScriptFromString:@"alert('done')"];
        return NO;
    }
    return YES;
}
JavaScript调用Objective-C:
//通知iPhone UIWebView 加载url对应的资源
//url的格式为:gap://something
function loadURL(url){
    var iFrame;
    iFrame = document.createElement("iFrame");
    iFrame.setAttribute("src",url); 
    iFrame.setAttribute("style","display:none;"); 
    iFrame.setAttribute("height","0px"); 
    iFrame.setAttribute("width","0px"); 
    iFrame.setAttribute("frameborder","0"); 
    document.body.appendChild(iFrame);
    //发起请求后这个iFrame就没用了,所以需要从dom中移除掉它
    iFrame.parentNode.removeChild(iFrame);
    iFrame = null;
}

最后,也可以使用第三方开源库实现相互调用的功能:
使用比较简单
WebViewJavaScriptBridge

上一篇 下一篇

猜你喜欢

热点阅读