用普通的UIWebView和JS交互 大概核心代码是这样的
- (void)setupWebView{
self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
self.webView.delegate = self;
NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSURL* url = [NSURL fileURLWithPath:path];
NSURLRequest* request = [NSURLRequest requestWithURL:url] ;
[self.webView loadRequest:request];
[self.view addSubview:self.webView];
}
代理方法
- (void)webViewDidFinishLoad:(UIWebView *)webView {
//获取js上下文
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//注入JS对象名称 "JSObjec"
self.jsContext[@"JSObjec"] = self;
self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
NSLog(@"异常信息:%@", exceptionValue);
};
}
想调用的OC方法
- (void)getCall:(NSString *)callString{
NSLog(@"Get----:%@", callString);
//此处填写相应的逻辑代码
}
然后JS代码
JS与OC交互
接下来是WKWebView的核心代码
需要导入头文件 代理
#import
#import
@interface ViewController ()
@property (nonatomic,strong) WKWebView *webView;
- (void)setupWKWebView{
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
// 设置偏好设置
config.preferences = [[WKPreferences alloc] init];
// 默认为0
config.preferences.minimumFontSize = 10;
// 默认认为YES
config.preferences.javaScriptEnabled = YES;
// 在iOS上默认为NO,表示不能自动通过窗口打开
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
config.processPool = [[WKProcessPool alloc] init];
config.userContentController = [[WKUserContentController alloc] init];
//注意在这里注入JS对象名称 "JSObjec"
[config.userContentController addScriptMessageHandler:self name:@"JSObjec"];
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
self.webView.navigationDelegate = self;
[self.view addSubview:self.webView];
NSURL *path = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
[self.webView loadRequest:[NSURLRequest requestWithURL:path]];
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"%@",message.body);//message.body这里面内容是js里传过来的参数
//message.name这个是注入的JS对象名称 "JSObjec"
if ([message.name isEqualToString:@"JSObjec"]) {
// 打印所传过来的参数,只支持NSNumber, NSString, NSDate, NSArray,
// NSDictionary, and NSNull类型
// 此处填写相应的逻辑代码
}
}
然后JS代码
JS与OC交互
好了 希望这篇总结能帮助到大家。
后续补充
//从OC中获取到一些数据后存入JS
NSString *sendToken = [NSString stringWithFormat:@"localStorage.setItem(\"accessToken\",'%@');",SecurityToken];
//WKUserScriptInjectionTimeAtDocumentStart JS加载前执行
//WKUserScriptInjectionTimeAtDocumentEnd JS加载后执行
//injectionTime配置不要写错 forMainFrameOnly NO(全局窗口) YES(只限主窗口)
WKUserScript *sendTokenScript = [[WKUserScript alloc]initWithSource:sendToken injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
//注入JS
[config.userContentController addUserScript:sendTokenScript];