iOS开发之JS与OC的混合开发

来源:互联网 发布:在线网络投资靠谱吗 编辑:程序博客网 时间:2024/05/16 16:17

JS调用原生OC

方式一

第一种方式是用JS发起一个假的URL请求,然后利用UIWebView的代理方法拦截这次请求,然后再做相应的处理。

我写了一个简单的HTML网页和一个btn点击事件用来与原生OC交互,HTML代码如下:

<html>

    <header>

        <metahttp-equiv="Content-Type"content="text/html; charset=utf-8" />

<scripttype="text/javascript">

            functionshowAlert(message){

                alert(message);

            }


            functionloadURL(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;

            }

            functionfirstClick() {

                loadURL("firstClick://shareClick?title=分享的标题&content=分享的内容&url=链接地址&imagePath=图片地址");

            }

        </script>

    </header>


    <body>

        <h2>这里是第一种方式 </h2>

        <br/>

        <br/>

        <buttontype="button"onclick="firstClick()">Click Me!</button>


    </body>

</html>

然后在项目的控制器中实现UIWebView的代理方法:

#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

{

    NSURL * url = [request URL];

   if ([[url scheme] isEqualToString:@"firstclick"]) {

        NSArray *params =[url.query componentsSeparatedByString:@"&"];


        NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];

        for (NSString *paramStrin params) {

            NSArray *dicArray = [paramStr componentsSeparatedByString:@"="];

            if (dicArray.count >1) {

                NSString *decodeValue = [dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

                [tempDic setObject:decodeValue forKey:dicArray[0]];

            }

        }

       UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式一" message:@"这是OC原生的弹出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];

       [alertView show];

       NSLog(@"tempDic:%@",tempDic);

        return NO;

    }


    return YES;

}

注意:1. JS中的firstClick,在拦截到的url scheme全都被转化为小写。

2.html中需要设置编码,否则中文参数可能会出现编码问题。

3.JS用打开一个iFrame的方式替代直接用document.location的方式,以避免多次请求,被替换覆盖的问题。

早期的JS与原生交互的开源库很多都是用得这种方式来实现的,例如:PhoneGapWebViewJavascriptBridge。关于这种方式调用OC方法,唐巧早期有篇文章有过介绍:

关于UIWebViewPhoneGap的总结

方式二

iOS 7之后,apple添加了一个新的库JavaScriptCore,用来做JS交互,因此JS与原生OC交互也变得简单了许多。

首先导入JavaScriptCore,然后在OC中获取JS的上下文

JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

再然后定义好JS需要调用的方法,例如JS要调用share方法:

则可以在UIWebView加载url完成后,在其代理方法中添加要调用的share方法:

- (void)webViewDidFinishLoad:(UIWebView *)webView

{

    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

    //定义好JS要调用的方法, share就是调用的share方法名

    context[@"share"] = ^() {

        NSLog(@"+++++++Begin Log+++++++");

        NSArray *args = [JSContext currentArguments];


        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式二" message:@"这是OC原生的弹出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];

        [alertView show];


        for (JSValue *jsValin args) {

            NSLog(@"%@", jsVal.toString);

        }


        NSLog(@"-------End Log-------");

    };

}

其中相对应的html部分如下:

<html>

    <header>

        <metahttp-equiv="Content-Type"content="text/html; charset=utf-8" />

        <scripttype="text/javascript">


            functionsecondClick() {

                share('分享的标题','分享的内容','图片地址');

            }


        functionshowAlert(message){

            alert(message);

        }


        </script>

    </header>


    <body>

        <h2>这里是第二种方式 </h2>

        <br/>

        <br/>

        <buttontype="button"onclick="secondClick()">Click Me!</button>


    </body>

</html>

JS部分确实要简单的多了。

OC调用JS

方式一

NSString *jsStr = [NSString stringWithFormat:@"showAlert('%@')",@"这里是JSalert弹出的message"];

[_webView stringByEvaluatingJavaScriptFromString:jsStr];

注意:该方法会同步返回一个字符串,因此是一个同步方法,可能会阻塞UI

方式二

继续使用JavaScriptCore库来做JS交互。

JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

NSString *textJS =@"showAlert('这里是JSalert弹出的message')";

[context evaluateScript:textJS];



本文有因为问题请联系

QQ:563699115

Telephone:18341266547



0 0