實現OC與JS的互動

來源:互聯網
上載者:User

實現OC與JS的互動
oc-->js stringByEvaluatingJavaScriptFromString,其參數是一NSString 字串內容是js代碼(這又可以是一個js函數、一句js代碼或他們的組合),當js函數有返回值或一句js代碼有值返回可通過stringByEvaluatingJavaScriptFromString的返回值擷取。

js-->oc 利用webView的重新導向原理(即重新在js中指定document.location的值,此為一url),只要在這個url字串中按自訂的規則指定好所需調用oc中的函數和參數,然後通過OC中的shouldStartLoadWithRequest函數去捕獲處理請求。


//APP調用webView載入的JS中的方法interfaceCalledByAPP,此例傳入了兩個參數- (void)sendMessage:(id)sender {    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"interfaceCalledByAPP(\"%@\",\"%@\")", @"2",@"333"]];}

//JS向APP傳值。首先實現UIWebView的代理,然後根據NSURLRequest的URL進行不同處理//JS中的將要傳遞的資料作為URL重新導向var tempurl = "將要傳遞的值";window.location.href= encodeURI(encodeURI(tempurl));

//webView的代理相應重新導向- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{    NSString *requestString = [[[request URL]  absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    NSLog(@"should-------");    if ([requestString hasPrefix:@"url://"]) {        //根據自己定義的規則,通過字串的值,調用OC的方法。這裡就輸出一下字串了。        NSLog(@"===%@",requestString);    }    return YES;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.