OC向JS传递参数
2017-07-22 本文已影响20人
smooth_lgh
- index.html的写法
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div style="margin-top: 20px">
<h2>JS与OC交互</h2>
<input type="button" value="OC给JS传值" onclick="tianbai.call()">
</div>
<script>
var Callback = function(name,password)
{
var str = name+password;
alert(str);
}
</script>
</body>
</html>
- 在ViewController文件中
#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
@interface ViewController ()<UIWebViewDelegate>
@property(nonatomic,strong) UIWebView *indexWebView;
@property(nonatomic,strong)JSContext *jsContext;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.indexWebView = [[UIWebView alloc]initWithFrame:self.view.bounds];
self.indexWebView.delegate = self;
NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSURL* url = [NSURL fileURLWithPath:path];
NSURLRequest* request = [NSURLRequest requestWithURL:url] ;
[self.indexWebView loadRequest:request];
}
#pragma mark - UIWebViewDelegate
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
self.jsContext[@"tianbai"] = self;
self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
NSLog(@"异常信息:%@", exceptionValue);
};
}
- (void)call{
NSLog(@"call");
// 之后在回调js的方法Callback把内容传出去
JSValue *Callback = self.jsContext[@"Callback"];
//传值给web端
[Callback callWithArguments:@[@"liuguanhua",@"123456"]];
}
- 效果图
其中 liuguanhua123456就是OC这边传递过来的参数.