1. 首先引入JavaScriptCore库
使用的时候导入头文件#import <JavaScriptCore/JavaScriptCore.h>
2. 本地一个html文件用做测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OC与JS交互</title>
<script>
function showAlert(){
ios_showMessage("点击了弹框按钮", arr);
}
function submit(){
alert('submit');
}
function ios_ocCalljs(dict, str){
var name = dict['name'];
var age = dict['age'];
alert(name + age + str);
// 传回去
showDict(dict)
}
</script>
</head>
<body>
<input id="submit" type="submit" value="我是提交" onclick="submit()"><br/>
<input type="button" value="弹框" onclick="showAlert()" /><br/>
<div/>
</body>
</html>
3. JavaScriptCore的OC与JS交互
// 加载完成
- (void)webViewDidFinishLoad:(UIWebView *)webView {
// OC 调用 JS --> stringByEvaluatingJavaScriptFromString
NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
self.navigationItem.title = title;
NSLog(@"****************华丽的分界线****************");
NSLog(@"加载完成咯!!!!");
// JSContext就为其提供着运行环境 H5上下文
JSContext *jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
// 保存全局变量
self.jsContext = jsContext;
// 异常处理
self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exception) {
NSLog(@"context = %@", context);
NSLog(@"exception = %@", exception);
};
// 提供全局变量
[self.jsContext evaluateScript:@"var arr = ['apple', 'orange', 'banna'];"];
// JS 调用 OC
self.jsContext[@"ios_showMessage"] = ^() {
NSLog(@"来了");
NSArray *args = [JSContext currentArguments];
NSLog(@"args = %@", args);
//OC调用JS 传参
NSDictionary *dict = @{@"name":@"spirej", @"age":@18};
[[JSContext currentContext][@"ios_ocCalljs"] callWithArguments:@[dict, @"love"]];
};
}
3.1 拿到H5上下文JSContext
// JSContext就为其提供着运行环境 H5上下文
JSContext *jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
3.2 JS调用OC
// JS 调用 OC
self.jsContext[@"ios_showMessage"] = ^() {
NSLog(@"来了");
NSArray *args = [JSContext currentArguments];
NSLog(@"args = %@", args);
};
ios_showMessage()是JS里定义的方法
3.3 OC调用JS
NSString *jsFunctStr = [NSString stringWithFormat:@"showAlert()"];
[self.jsContext evaluateScript:jsFunctStr];
ios_ocCalljs()是JS里定义的方法,OC调用并可传参
4. JS操作OC对象
4.1 声明一个SP_JSObject类
#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SPProtocol <JSExport>
- (void)doSomething;
- (void)doSomething2:(NSString *)str;
// 协议 - 协议方法
JSExportAs(getS, - (int)getSum:(int)num1 num2:(int)num2);
@end
@interface SP_JSObject : NSObject<SPProtocol>
@end
NS_ASSUME_NONNULL_END
自定义的协议方法
- (void)doSomething {
NSLog(@"doSomething 来了");
}
- (void)doSomething2:(NSString *)str {
NSLog(@"doSomething2 来了 -- %@", str);
}
- (int)getSum:(int)num1 num2:(int)num2 {
NSLog(@"getSum 来了");
// int (nil) - jsvalue (0)
NSLog(@"num1 = %d, num2 = %d", num1, num2);
return num1+num2;
}
JS里面有这样一个方法,分别调用了SP_JSObject对象的协议方法
function controlObject(){
spObject.doSomething();
spObject.doSomething2("艾欧尼亚");
spObject.getS(10, 20);
}
在OC端初始化SP_JSObject对象,并赋给JS端,JS端就可调起SP_JSObject的对象方法
// JS 操作对象
SP_JSObject *spObject = [[SP_JSObject alloc] init];
self.jsContext[@"spObject"] = spObject;
4. demo JS与OC交互,打开手机相册
4.1 JS端有一个打开相册的button和响应方法,还有一个显示图片的方法
function openAlbumImage(){
getImage();
}
function showImage(imageDataStr){
var tz_img = document.getElementById("tz_image");
tz_img.innerHTML = "<image style='width:200px;' src='data:image/png;base64,"+imageDataStr+"'>";
}
<input type="button" value="打开相册" onclick="openAlbumImage()" /><br />
4.2 遵循协议,并声明相册控制器
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic,strong) UIImagePickerController *imagePicker;
4.3 JS交互OC,初始化相册控制器
// 打开相册
__weak typeof(self) weakSelf = self;
self.jsContext[@"getImage"] = ^() {
weakSelf.imagePicker = [[UIImagePickerController alloc] init];
weakSelf.imagePicker.delegate = weakSelf;
weakSelf.imagePicker.allowsEditing = YES;
weakSelf.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[weakSelf presentViewController:weakSelf.imagePicker animated:YES completion:nil];
};
4.4 实现协议方法,最后OC调JS传图片给JS显示
#pragma mark -- UIImagePickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
NSLog(@"info---%@",info);
UIImage *resultImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
NSData *imgData = UIImageJPEGRepresentation(resultImage, 0.01);
NSString *encodedImageStr = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
[self removeSpaceAndNewline:encodedImageStr];
[self dismissViewControllerAnimated:YES completion:nil];
NSString *imageString = [self removeSpaceAndNewline:encodedImageStr];
// 拿到图片后,调用JS方法,把图片传给JS显示
NSString *jsFunctStr = [NSString stringWithFormat:@"showImage('%@')",imageString];
[self.jsContext evaluateScript:jsFunctStr];
}
- (NSString *)removeSpaceAndNewline:(NSString *)str
{
NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
return temp;
}
文中所有示例demo可以在这里下载
https://github.com/SPIREJ/OCJS