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;
}
原文:http://www.cnblogs.com/lcchuguo/p/5099939.html