OC與JS的互動,OCJS互動

來源:互聯網
上載者:User

OC與JS的互動,OCJS互動

現在APP的開發已經不局限於原生開發,很多都是原生+html5這種混合開發

我們可以通過webView這個控制項,實現混合開發。

1.首先你需要建立一個html頁面

<html>    <head>        <meta charset="utf-8">        <title>第一個頁面</title>    </head>        <script>        function login() {            location.href = 'ddz://call_?200';        }    </script>        <body>        <button style="background: blue; width:100px; height:30px" onclick="login()">確定</button>        <br>        <a href="http://www.baidu.com">百度</a>    </body></html>

在app初始化時,載入這個頁面

- (void)viewDidLoad {    [super viewDidLoad];        [self.webView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"]]];}

2.實現UIWebViewDelegate這個協議

利用stringByEvaluationgJavaScriptFromString這個協議方法,

可以完成OC調用JS

#pragma mark - <UIWebViewDelegate>- (void)webViewDidFinishLoad:(UIWebView *)webView {    [webView stringByEvaluatingJavaScriptFromString:@"alert(100)"];}

3.

利用shouldStartLoadWithRequest這個方法可以完成JS調用OC

/** * 通過這個方法完成JS調用OC * 第三方架構 :WebViewJavaScriptBridge */- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {    //url = ddz://sendMessage_?200    NSString *url = request.URL.absoluteString;    NSString *scheme = @"ddz://";    if ([url hasPrefix:@"ddz://"]) {        NSLog(@"調用OC的方法");                //獲得協議後面的路徑 path = sendMessage_?200        NSString *path = [url substringFromIndex:scheme.length];        //利用?進行切割        NSArray *subpaths = [path componentsSeparatedByString:@"?"];        //方法名 methodName = sendMessage:        NSString *methodName = [[subpaths firstObject] stringByReplacingOccurrencesOfString:@"_" withString:@":"];        //參數 params = 200        NSString *params = [subpaths lastObject];                [self performSelector:NSSelectorFromString(methodName) withObject:params];//        NSLog(@"%@",subpaths);        return NO;    }        NSLog(@"想載入其他請求,不是想調用OC的方法");        return YES;}

4.

在github上也找到了一個 oc 和 js 之間能夠互動的類,可以看一下 https://github.com/marcuswestin/WebViewJavascriptBridge

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.