用普通的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對(duì)象名稱 "JSObjec"
self.jsContext[@"JSObjec"] = self;
self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
NSLog(@"異常信息:%@", exceptionValue);
};
}
想調(diào)用的OC方法
- (void)getCall:(NSString *)callString{
NSLog(@"Get----:%@", callString);
//此處填寫(xiě)相應(yīng)的邏輯代碼
}
然后JS代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div style="margin-top: 20px">
<h2>JS與OC交互</h2>
<input type="button" value="喚起本地方法(call)" onclick="JSObjec.call()">
</div>
<script>
var call = function()
{
var callInfo = JSON.stringify("www.itdecent.cn");//此處參數(shù)可自定義
JSObjec.getCall(callInfo);
}
</script>
</body>
</html>
接下來(lái)是WKWebView的核心代碼
需要導(dǎo)入頭文件 代理
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
@interface ViewController ()<WKNavigationDelegate,WKScriptMessageHandler>
@property (nonatomic,strong) WKWebView *webView;
- (void)setupWKWebView{
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
// 設(shè)置偏好設(shè)置
config.preferences = [[WKPreferences alloc] init];
// 默認(rèn)為0
config.preferences.minimumFontSize = 10;
// 默認(rèn)認(rèn)為YES
config.preferences.javaScriptEnabled = YES;
// 在iOS上默認(rèn)為NO,表示不能自動(dòng)通過(guò)窗口打開(kāi)
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
config.processPool = [[WKProcessPool alloc] init];
config.userContentController = [[WKUserContentController alloc] init];
//注意在這里注入JS對(duì)象名稱 "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這里面內(nèi)容是js里傳過(guò)來(lái)的參數(shù)
//message.name這個(gè)是注入的JS對(duì)象名稱 "JSObjec"
if ([message.name isEqualToString:@"JSObjec"]) {
// 打印所傳過(guò)來(lái)的參數(shù),只支持NSNumber, NSString, NSDate, NSArray,
// NSDictionary, and NSNull類型
// 此處填寫(xiě)相應(yīng)的邏輯代碼
}
}
然后JS代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div style="margin-top: 20px">
<h2>JS與OC交互</h2>
<input type="button" value="喚起本地方法(call)" onclick="JSObjec.call()">
</div>
<script>
var call = function()
{
var callInfo = JSON.stringify("www.itdecent.cn");//此處參數(shù)可自定義
//這里的內(nèi)容差不多全部一樣 只是調(diào)用的方法有區(qū)別 一定要注意區(qū)分
//這個(gè)是用UIWebView時(shí)調(diào)用的方法 JSObjec.getCall(callInfo);
//下面是用WKWebView調(diào)用的方法
window.webkit.messageHandlers.JSObjec.postMessage(callInfo);
}
</script>
</body>
</html>
好了 希望這篇總結(jié)能幫助到大家。
后續(xù)補(bǔ)充
//從OC中獲取到一些數(shù)據(jù)后存入JS
NSString *sendToken = [NSString stringWithFormat:@"localStorage.setItem(\"accessToken\",'%@');",SecurityToken];
//WKUserScriptInjectionTimeAtDocumentStart JS加載前執(zhí)行
//WKUserScriptInjectionTimeAtDocumentEnd JS加載后執(zhí)行
//injectionTime配置不要寫(xiě)錯(cuò) forMainFrameOnly NO(全局窗口) YES(只限主窗口)
WKUserScript *sendTokenScript = [[WKUserScript alloc]initWithSource:sendToken injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
//注入JS
[config.userContentController addUserScript:sendTokenScript];