1. 程式人生 > >iOS下JS與原生OC互相呼叫

iOS下JS與原生OC互相呼叫

iOS開發免不了要與UIWebView打交道,然後就要涉及到JS與原生OC互動,今天總結一下JS與原生OC互動的兩種方式。

JS呼叫原生OC篇

方式一

第一種方式是用JS發起一個假的URL請求,然後利用UIWebView的代理方法攔截這次請求,然後再做相應的處理。
我寫了一個簡單的HTML網頁和一個btn點選事件用來與原生OC互動,HTML程式碼如下:

<html>
    <header>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
            function showAlert(message){
                alert(message);
            }

            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;
            }
            function firstClick() {
                loadURL("firstClick://shareClick?title=分享的標題&content=分享的內容&url=連結地址&imagePath=圖片地址");
            }
        </script>
    </header>

    <body>
        <h2> 這裡是第一種方式 </h2>
        <br/>
        <br/>
        <button type="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 *paramStr in 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的方式,以避免多次請求,被替換覆蓋的問題。

方式二

在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 *jsVal in args) {
            NSLog(@"%@", jsVal.toString);
        }

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

其中相對應的html部分如下:
<html>
    <header>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">

            function secondClick() {
                share('分享的標題','分享的內容','圖片地址');
            }

        function showAlert(message){
            alert(message);
        }

        </script>
    </header>

    <body>
        <h2> 這裡是第二種方式 </h2>
        <br/>
        <br/>
        <button type="button" onclick="secondClick()">Click Me!</button>

    </body>
</html>

JS部分確實要簡單的多了。

OC呼叫JS篇

方式一

NSString *jsStr = [NSString stringWithFormat:@"showAlert('%@')",@"這裡是JS中alert彈出的message"];
[_webView stringByEvaluatingJavaScriptFromString:jsStr];

注意:該方法會同步返回一個字串,因此是一個同步方法,可能會阻塞UI。
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
NSString *textJS = @"showAlert('這裡是JS中alert彈出的message')";
[context evaluateScript:textJS];