@property (nonatomic, weak) JSContext *jsContext;
@property (nonatomic, weak) UIWebView *webView;
@end
实现这个模型:
@implementation HYBJsObjCModel
- (void)callWithDict:(NSDictionary *)params {
NSLog(@"Js调用了OC的方法,参数为:%@", params);
}
// Js调用了callSystemCamera
- (void)callSystemCamera {
NSLog(@"JS调用了OC的方法,调起系统相册");
// JS调用后OC后,又通过OC调用JS,但是这个是没有传参数的
JSValue *jsFunc = self.jsContext[@"jsFunc"];
[jsFunc callWithArguments:nil];
}
- (void)jsCallObjcAndObjcCallJsWithDict:(NSDictionary *)params {
NSLog(@"jsCallObjcAndObjcCallJsWithDict was called, params is %@", params);
// 调用JS的方法
JSValue *jsParamFunc = self.jsContext[@"jsParamFunc"];
[jsParamFunc callWithArguments:@[@{@"age": @10, @"name": @"lili", @"height": @158}]];
}
- (void)showAlert:(NSString *)title msg:(NSString *)msg {
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *a = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[a show];
});
}
@end
接下来,我们在controller中在webview加载完成的代理中,给JS注入模型。
#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
// 通过模型调用方法,这种方式更好些。
HYBJsObjCModel *model = [[HYBJsObjCModel alloc] init];
self.jsContext[@"OCModel"] = model;
model.jsContext = self.jsContext;
model.webView = self.webView;
self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
NSLog(@"异常信息:%@", exceptionValue);
};
}
我们是通过webView的valueForKeyPath获取的,其路径为documentView.webView.mainFrame.javaScriptContext。
这样就可以获取到JS的context,然后为这个context注入我们的模型对象。
我们先写两个JS方法:
var jsFunc = function() {
alert(‘Objective-C call js to show alert‘);
}
var jsParamFunc = function(argument) {
document.getElementById(‘jsParamFuncSpan‘).innerHTML
= argument[‘name‘];
}
这里我们定义了两个JS方法,一个是jsFunc,不带参数。
另一个是jsParamFunc,带一个参数。
接下来,我们在html中的body中添加以下代码:
Test how to use objective-c call js
现在就可以测试代码了。
当我们点击第一个按钮:Call ObjC system camera时,
通过OCModel.callSystemCamera(),就可以在HTML中通过JS调用OC的方法。
在OC代码中,我们的callSystemCamera方法体中,添加了以下两行代码,就是获取HTML中所定义的JS就去jsFunc,然后调用它。
JSValue *jsFunc = self.jsContext[@"jsFunc"];
[jsFunc callWithArguments:nil];
这样就可以在JS调用OC方法时,也让OC反馈给JS。
看看下面传字典参数:
- (void)jsCallObjcAndObjcCallJsWithDict:(NSDictionary *)params {
NSLog(@"jsCallObjcAndObjcCallJsWithDict was called, params is %@", params);
// 调用JS的方法
JSValue *jsParamFunc = self.jsContext[@"jsParamFunc"];
[jsParamFunc callWithArguments:@[@{@"age": @10, @"name": @"lili", @"height": @158}]];
}
获取我们在HTML中定义的jsParamFunc方法,然后调用它并传了一个字典作为参数。iOS与JS交互实战篇(ObjC版)
原文:http://www.cnblogs.com/Mrliheng/p/5825672.html