http://blog.csdn.net/y550918116j/article/details/48733443
一、核心原理
stringByEvaluatingJavaScriptFromString,其参数是一NSString 字符串内容是js代码(这又可以是一个js函数、一句js代码或他们的组合),当js函数有返回值或一句js代码有值返回可通过stringByEvaluatingJavaScriptFromString的返回值获取。
利用webView的重定向原理(即重新在js中指定document.location的值,此为一url),只要在这个url字符串中按自定义的规则指定好所需调用oc中的函数和参数,然后通过OC中的shouldStartLoadWithRequest函数去捕获处理请求。
二、OC源代码
#import@interfaceViewController:UIViewController
@end
2. ViewController.m实现
#import"ViewController.h"
@interfaceViewController()
@end
@implementation
ViewController
- (void)viewDidLoad{
[superviewDidLoad];
// 初始化UIWebViewUIWebView*web = [[UIWebViewalloc] initWithFrame:self.view.bounds]; web.delegate=self; [web setScalesPageToFit:YES]; [self.viewaddSubview:web];//加载网页NSURL*url = [NSURLURLWithString:@"http://192.192.102.111:8080/test.html"]; [web loadRequest:[NSURLRequestrequestWithURL:url]];}#pragma mark - UIWebViewDelegate实现#pragma mark 开始加载网页- (void)webViewDidStartLoad:(UIWebView*)webView{NSLog(@"开始加载网页");}#pragma mark 网页加载完成- (void)webViewDidFinishLoad:(UIWebView*)webView{NSLog(@"网页加载完成,调用JS代码\n--------------"); [webView stringByEvaluatingJavaScriptFromString:@"ocUICall('阳君')"];}#pragma mark 网页加载出错- (void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error{NSLog(@"网页加载出错:%@", error);}#pragma mark 网页监听- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType{// 过滤NSString*requestString = [[request.URLabsoluteString]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];;// 分割NSArray*urlComps = [requestString componentsSeparatedByString:@"::"];if([urlComps count] ==3&& [@"ios"isEqualToString:[urlComps objectAtIndex:0]]) {//解析约定的指令// 方法名NSString*methods = [NSStringstringWithFormat:@"%@:", [urlComps objectAtIndex:1]];// 携带的参数NSString*params = [urlComps objectAtIndex:2];NSLog(@"JS调用OC代码->UIWebView\n方法名:%@,参数:%@", methods, params); SEL selector = NSSelectorFromString(methods);// 判断类是否有方法if( [ViewController instancesRespondToSelector:selector]) {// 执行方法,携带参数[selfperformSelector:selector withObject:params]; }else{NSLog(@"没有提供调用的%@方法名",methods); }returnNO; }returnYES;}@end
三、JS源代码
// UIWebView调用functionocUICall(params){// 方法名varmethod ="test";// 组装请求数据varurl ="ios::"+ method +"::"+ params;// 发起请求document.location = url;}