?1.OC调?用JS - OC传递数据给JS ?1> 利?用UIWebView的某个?方法执?行JS代码 ?NSString *result = [webView stringByEvaluatingJavaScriptFromString:js]; ?// result是执?行完JS代码后的返回值 ?// 其实也可以通过这个?方法办到:JS传递数据给OC ?2> 举例 ?NSString *username = @"zhangsan"; ?NSString *pwd = @"888888"; ?NSMutableString *js = [NSMutableString string]; ?[js appendString:@"function login(username, pwd) { alert(username + ‘-‘ + ?pwd);}"]; ?[js appendFormat:@"login(‘%@‘, ‘%@‘);", username, pwd]; ?// 在OC中调?用JS的函数(执?行JS代码) ?[webView stringByEvaluatingJavaScriptFromString:js]; ?2.JS调?用OC - JS传递数据给OC /* 通用url的设计 协议固定: xxx: 一般有2个参数: 1> 方法名 2> 方法参数 */ NSString *onload = @"this.onclick = function() {" " window.location.href = ‘xxx:saveImageToAlbum:&‘ + this.src;" "};"; [imgHtml appendFormat:@"<img onload=\"%@\" width=\"%d\" height=\"%d\" src=\"%@\">", onload, width, height, img.src]; #pragma mark - <UIWebViewDelegate> /** * 每当webView发送一个请求之前都会先调用这个方法 * * @param request 即将发送的请求 * * @return YES: 允许发送这个请求, NO: 禁止发送这个请求 */ - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *url = request.URL.absoluteString; // xxx:call:&10086 // xxx:sendMsg:body:&10086&2434 NSRange range = [url rangeOfString:@"xxx:"]; if (range.location != NSNotFound) { NSUInteger loc = range.location + range.length; NSString *path = [url substringFromIndex:loc]; // 获得方法和参数 NSArray *methodNameAndParam = [path componentsSeparatedByString:@"&"]; // 方法名 NSString *methodName = [methodNameAndParam firstObject]; // 调用方法 SEL selector = NSSelectorFromString(methodName); if ([self respondsToSelector:selector]) { // 判断方法的目的: 防止因为方法不存在而报错 NSMutableArray *params = nil; if (methodNameAndParam.count > 1) { // 方法有参数 params = [NSMutableArray arrayWithArray:methodNameAndParam]; // 从数组中去掉方法名 [params removeObjectAtIndex:0]; } [self performSelector:selector withObjects:params]; } return NO; } return YES; } 这里用到 performSelector: withObjects 方法 传递多个参数: - (id)performSelector:(SEL)selector withObjects:(NSArray *)objects { NSMethodSignature *signature = [self methodSignatureForSelector:selector]; if (signature) { NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature]; [invocation setTarget:self]; [invocation setSelector:selector]; for(int i = 0; i < [objects count]; i++){ id object = [objects objectAtIndex:i]; [invocation setArgument:&object atIndex: (i + 2)]; } [invocation invoke]; if (signature.methodReturnLength) { id anObject; [invocation getReturnValue:&anObject]; return anObject; } else { return nil; } } else { return nil; } }
原文:http://www.cnblogs.com/DarbyCJ/p/4646530.html