通过JavaScriptCore实现OC与JS的交互
1 OC调用JS
NSString *versionCodeStr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
NSString *jsStr = [NSString stringWithFormat:@"appVersionCode('%@')", versionCodeStr];
[self.myWebView stringByEvaluatingJavaScriptFromString:jsStr];
在JS中JavaScript代码如下
function appVersionCode(versionCode){
alert(versionCode)
}
2 JS调用OC
2.1 block 方式
JSContext *context = [NSObject contextForWebView:self.myWebView];
context[@"startLoad"] = ^ (NSString *flag) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"开始就添加");
});
};
context[@"callShareAction"] = ^ (NSString *flag) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"分享");
});
};
context[@"callReturnAction"] = ^ () {
return @"最幸福的一天";
};
在JS中调用方式如下
var callShare = function() {
callShareAction(1)
}
var callAlert = function () {
var str = callReturnAction()
alert(str)
}
window.onload = function () {
startLoad(1)
}
2.2 注入模型的方式
JSContext *context = [NSObject contextForWebView:self.myWebView];
DMCallCameraModel *callCameraModel = [[DMCallCameraModel alloc] init];
context[@"callCameraModel"] = callCameraModel;
模型的定义,需要遵循JSExport协议
#import
#import
@protocol DMCallCameraExport
- (void)callCameraAction:(BOOL)bFlag;
- (void)callMultiArgumentsAction:(NSString *)firstStr titleStr:(NSString *)secondStr;
@end
@interface DMCallCameraModel : NSObject
@end
模型的实现
- (void)callCameraAction:(BOOL)bFlag
{
NSLog(@"callCameraAction");
}
- (void)callMultiArgumentsAction:(NSString *)firstStr titleStr:(NSString *)secondStr
{
NSLog(@"参数一:%@, 参数二:%@", firstStr, secondStr);
}
@end
在JS中的调用方式如下
var callCamera = function() {
callCameraModel.callCameraAction(1)
}
var callSubmit = function() {
callCameraModel.callMultiArgumentsActionTitleStr("Hello", "World")
}
注:多个参数时,在JS中调用时使用驼峰法并去掉冒号
3 关于JSContext的获取时机
#import
#import
@interface NSObject (JSContextTracker)
+ (JSContext *)contextForWebView:(UIWebView *)webView;
@end
#import "NSObject+JSContextTracker.h"
#import "DMNotificationName.h"
@implementation NSObject (JSContextTracker)
+ (NSMapTable *)JSContextTrackerMap
{
static NSMapTable *contextTracker;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
contextTracker = [NSMapTable strongToWeakObjectsMapTable];
});
return contextTracker;
}
- (void)webView:(id)unused didCreateJavaScriptContext:(JSContext *)ctx forFrame:(id)alsoUnused
{
NSAssert([ctx isKindOfClass:[JSContext class]], @"bad context");
if (!ctx)
return;
NSMapTable *map = [NSObject JSContextTrackerMap];
static long contexts = 0;
NSString *contextKey = [NSString stringWithFormat:@"jsctx_%@", @(contexts++)];
[map setObject:ctx forKey:contextKey];
ctx[@"JSContextTrackerMapKey"] = contextKey; // store the key to the map in the context itself
[[NSNotificationCenter defaultCenter] postNotificationName:DMWebviewCreateContextNotification object:nil];
}
+ (JSContext *)contextForWebView:(UIWebView *)webView
{
// this will trigger didCreateJavaScriptContext if it hasn't already been called
NSString *contextKey = [webView stringByEvaluatingJavaScriptFromString:@"JSContextTrackerMapKey"];
JSContext *ctx = [[NSObject JSContextTrackerMap] objectForKey:contextKey];
return ctx;
}
@end
我们观察通知,并通过contextForWebView方法获取JSContext
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(webViewDidCreateContext:) name:DMWebviewCreateContextNotification object:nil];
- (void)webViewDidCreateContext:(NSNotification *)notify
{
if (self.isShowing) {
NSLog(@"*********** 页面正在显示 **************");
} else {
NSLog(@"*********** 页面已经消失 **************");
return;
}
JSContext *context = [NSObject contextForWebView:self.myWebView];
}
4 JS中的代码如下
Objective-C和JavaScript交互的那些事
5 效果如下
点击CallCamera、Share、Submit输出log如下
点击弹窗如下
- (void)alertBtnClicked:(id)sender
{
[self.myWebView stringByEvaluatingJavaScriptFromString:@"callAlert()"];
}
先OC调用JS的callAlert方法,callAlert方法中JS有调用OC的callReturnAction方法返回字符串,然后JS中弹出返回的字符串
点击保存如下
- (void)saveBtnClicked:(id)sender
{
NSString *versionCodeStr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
NSString *jsStr = [NSString stringWithFormat:@"appVersionCode('%@')", versionCodeStr];
[self.myWebView stringByEvaluatingJavaScriptFromString:jsStr];
}