1.Oc调用Js方法
(1)JS调用OC-URL方法
示例1、准备一个本地化的html网页,如jsIOS.html
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>js调用oc</title>
<script type="text/javaScript">
function postStr(){
return document.getElementById("text1").value;
//return "javaScript返回值啦";
}
</script>
</head>
<body>
<p><input type="text" id="text1" value="返回值"/></p>
<p><input type="button" id="btn" value="提交" onclick="postStr()"/></p>
</body>
</html>
2、将此html文件放到项目代码目录里面,如图:
3、拖一个UIWebView控件和UIButton控件到xxxViewController对应的.xib或.storyboard视图的UIView上;
在xxxViewController的.h文件中分别声明UIWebView类型变量和UIButton类型的变量,以及一个按钮点击事件(并且跟视图里面的控件连线),
并且添加一个UIWebViewDelegate类型的委托。
xxxViewController.h文件内容如下:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UIWebViewDelegate>
@property(nonatomic,retain) IBOutlet UIWebView *webview;
@property(nonatomic,retain) IBOutlet UIButton *button;
-(IBAction)IOS_JS:(id)sender;
@end
4、在xxxViewController.m文件中实现通过点击事件,调用javaScript的方法并取得返回值。
代码如下:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize webview;
- (void)viewDidLoad
{
[super viewDidLoad];
//设置webView
webview.backgroundColor = [UIColor clearColor];
//webview.scalesPageToFit =YES;
webview.delegate =self;
//找到jsIOS.html文件的路径
NSString *basePath = [[NSBundle mainBundle]bundlePath];
NSString *helpHtmlPath = [basePath stringByAppendingPathComponent:@"jsIOS.html"];
NSURL *url = [NSURL fileURLWithPath:helpHtmlPath];
//加载本地html文件
[webview loadRequest:[NSURLRequest requestWithURL:url]];
}
/*
* 点击事件
* 调用javaScript的方法postStr()并取得返回值
* 输出返回值到控制台
*/
-(IBAction)IOS_JS:(id)sender
{
NSString *str = [self.webview stringByEvaluatingJavaScriptFromString:@"postStr();"];
NSLog(@"JS返回值:%@",str);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
(2)JS调用OC第二方法(JavaScriptCore)
首先我导入
#import <JavaScriptCore/JavaScriptCore.h>
方法如下
点击Linked Frameworks and Libraries 的添加后 选择 JavaScriptCore.framework
选中JavaScriptCore.framework后 点击右下角Add 添加完成
好 创建完成之后我们导入一下头文件
点进去 会看到如下几个方法
#import "JSContext.h"
#import "JSValue.h"
#import "JSManagedValue.h"
#import "JSVirtualMachine.h"
#import "JSExport.h"
这些方法我们等会再细讲
下来我们创建一个UIWebView 用来测试
创建UIWebView
初始化,添加,打开网址
运行效果如下
下面我们来实现UIWebView的几个代理方法
首先我们看下它的代理方法
每个方法的作用等会在带里面做注释首先我们添加协议
实现代理方法每个方法是什么时候调用都在注释里面
下来我们先尝试用oc调用一下js方法
执行效果如下:
Js调用Oc方法
(1)JS调用OC-URL方法"
- (void)viewDidLoad {
[super viewDidLoad];
self.title =@"URL方法";
[self loadWeb];
}
- (void)loadWeb
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"JStoOCfirstIndex.html" ofType:nil];
NSString *htmlString = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
}
#pragma mark - webView的delegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *getURLString = [request.URL absoluteString];
NSLog(@"总的字符串:%@",getURLString);
NSString *htmlHeadString = @"zimu://";
//协议头可以自己定义可以自己定义
if([getURLString hasPrefix:htmlHeadString])
{
NSString *subString = [getURLString substringFromIndex:htmlHeadString.length];
NSArray *arrayStr = [subString componentsSeparatedByString:@"?"];
NSString *fistStr = [arrayStr firstObject];
NSString *methodName = [fistStr stringByReplacingOccurrencesOfString:@"_" withString:@":"];
SEL selector = NSSelectorFromString(methodName);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
//-Warc-performSelector-leaks为唯一的警告标识
[self performSelector:selector withObject:[arrayStr lastObject]];
#pragma clang diagnostic pop
//注意:系统提供的方法最多只有两个参数,如果要多个参数,使用我的扩展类
// - (id)performSelector:(SEL)aSelector withObjects:(NSArray *)objects
return NO;
}
else
return YES;
}
- (void)callName:(NSString *)string
{
NSLog(@"详细讲解网站是:\n%@",string);
[LZBAlterView lzb_alterViewWithText:[NSString stringWithFormat:@"传过来的参数:%@",string] OneTitle:@"知道了" TwoTitle:nil ThreeTitle:nil handleBlock:^(LZBAlterView *alterView, NSInteger btntag) {
[alterView removeAlterView];
}];
}
(2) OC 调用 JS 第二方法 (JavaScriptCore)- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"OC调用JS方法";
[self loadWebData];
[self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc]initWithCustomView:self.btn]];
}
- (void)loadWebData
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"OCtoJStwoIndex.html" ofType:nil];
NSURL *localURL = [[NSURL alloc]initFileURLWithPath:path];
[self.webView loadRequest:[NSURLRequest requestWithURL:localURL]];
}
- (void)handdleOCCallJS
{
//获得WebView的运行环境的对象
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//调用方法(注意:这里是JS里面的定义的方法)
NSString *callJSstring = @"sendJSString('参数:OC call JS test 子木')";
[context evaluateScript:callJSstring];
}
- (UIButton *)btn
{
if(_btn == nil)
{
_btn = [UIButton buttonWithType:UIButtonTypeCustom];
_btn.backgroundColor = [UIColor redColor];
_btn.frame = CGRectMake(self.view.center.x - button_Width * 0.5, self.view.center.y, button_Width, button_Height);
[_btn setTitle:@"点击调用JS" forState:UIControlStateNormal];
[_btn addTarget:self action:@selector(handdleOCCallJS) forControlEvents:UIControlEventTouchUpInside];
}
return _btn;
}