實現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;}