WKWebViewConfiguration
注入WKScriptMessageHandler
,由前端下發(fā)數(shù)據(jù),客戶端根據(jù)相關(guān)的數(shù)據(jù)作出相應(yīng)的操作,OC
代碼如下:
- (WKWebView *)wkWebView {
if (!_wkWebView) {
// 進行配置控制器
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
// 實例化對象
configuration.userContentController = [WKUserContentController new];
// 調(diào)用JS方法
[configuration.userContentController addScriptMessageHandler:self name:@"NativeModel"];
// 進行偏好設(shè)置
WKPreferences *preferences = [WKPreferences new];
preferences.javaScriptCanOpenWindowsAutomatically = YES;
// preferences.minimumFontSize = 20.0;
configuration.preferences = preferences;
// 初始化WKWebView
_wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, kNavigationBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) configuration:configuration];
_wkWebView.UIDelegate = self;
_wkWebView.navigationDelegate =self;
}
return _wkWebView;
}
[self.view addSubview:self.wkWebView];
[self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
@interface ViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>
//webView
@property (nonatomic, strong) WKWebView *wkWebView;
@end
- 實現(xiàn)
WKScriptMessageHandler
代理方法,并在該代理方法中根據(jù)相應(yīng)的注入js
的名稱,實現(xiàn)對應(yīng)的邏輯
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"NativeModel"]) {
NSDictionary *jsData = message.body;
NSLog(@"%@", message.name);
//讀取js function的字符串
// NSString *jsFunctionString = jsData[@"result"];
// //拼接調(diào)用該方法的js字符串(convertDictionaryToJson:方法將NSDictionary轉(zhuǎn)成JSON格式的字符串)
// NSString *jsonString = [NSDictionary convertDictionaryToJson:@{@"test":@"123", @"data":@"666"}];
// NSString *jsCallBack = [NSString stringWithFormat:@"(%@)(%@);", jsFunctionString, jsonString];
// //執(zhí)行回調(diào)
// [self.weWebView evaluateJavaScript:jsCallBack completionHandler:^(id _Nullable result, NSError * _Nullable error) {
// if (error) {
// NSLog(@"err is %@", error.domain);
// }
// }];
}
}
前端代碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>html5page-oc</title>
<script>
function btn1Click() {
window.webkit.messageHandlers.NativeModel.postMessage({name: 'zhangyutang', age: 12});
alert("after call");
}
</script>
</head>
<body>
<input type="button" value="button c" onclick="btn1Click()">
</body>
</html>
使用WKWebView
向js
傳值
OC
代碼如下
- (WKWebView *)wkWebView {
if (!_wkWebView) {
// 進行配置控制器
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
// 實例化對象
configuration.userContentController = [WKUserContentController new];
// 調(diào)用JS方法
[configuration.userContentController addScriptMessageHandler:self name:@"NativeModel"];
// 進行偏好設(shè)置
WKPreferences *preferences = [WKPreferences new];
preferences.javaScriptCanOpenWindowsAutomatically = YES;
// preferences.minimumFontSize = 20.0;
configuration.preferences = preferences;
// 初始化WKWebView
_wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, kNavigationBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) configuration:configuration];
_wkWebView.UIDelegate = self;
_wkWebView.navigationDelegate =self;
}
return _wkWebView;
}
[self.view addSubview:self.wkWebView];
[self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
@interface ViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>
//webView
@property (nonatomic, strong) WKWebView *wkWebView;
@end
- 實現(xiàn)代理方法,在協(xié)議加載完
WebView
后,注入相應(yīng)的js
,將需要上傳的參數(shù)上傳給前端
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
NSMutableDictionary *dic = [NSMutableDictionary new];
dic[@"username"] = @"里斯";
dic[@"token"] = @"1198203";
dic[@"avatar"] = @"";
NSString *jsonStr = [self convertToJsonData:dic];
NSString * jsStr = [NSString stringWithFormat:@"sendKey('%@')",jsonStr];
[self.wkWebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//此處可以打印error.
}];
}
-(NSString *)convertToJsonData:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString;
if (!jsonData) {
NSLog(@"%@",error);
}else{
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
NSRange range = {0,jsonString.length};
//去掉字符串中的空格
[mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
NSRange range2 = {0,mutStr.length};
//去掉字符串中的換行符
[mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
return mutStr;
}
前端代碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div onclick="newway()">新方法</div>
<input type="text" id = "show1">
<input type="text" id = "show2">
<input type="text" id = "show3">
</body>
<script src="js/jquery-2.1.4.js"></script>
<script>
function newway(){
alert("newway")
// var val = '{"token":"1198203","username":"張三","avatar":""}'
// sendKey(val)
}
function sendKey(val){
alert("sendKey")
let iOSInfo = JSON.parse(val);
$("#show1").val(iOSInfo.username)
$("#show2").val(iOSInfo.token)
$("#show3").val(iOSInfo.avatar)
}
</script>
</html>
遇到的問題
- 上傳參數(shù)到前端,注入js時出現(xiàn)
Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={NSLocalizedDescription=A JavaScript exception occurred
錯誤,檢查上傳的JSON
是否正確,保證上傳的JSON
是一個正確的JSON
即可