ios WKWebView和js交互

2022-01-06  本文已影响0人  coder小鹏

WKWebViewConfiguration注入WKScriptMessageHandler,由前端下发数据,客户端根据相关的数据作出相应的操作,OC代码如下:

- (WKWebView *)wkWebView {
    if (!_wkWebView) {
        // 进行配置控制器
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        // 实例化对象
        configuration.userContentController = [WKUserContentController new];
        // 调用JS方法
        [configuration.userContentController addScriptMessageHandler:self name:@"NativeModel"];
        
        // 进行偏好设置
        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

- (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"];
//        //拼接调用该方法的js字符串(convertDictionaryToJson:方法将NSDictionary转成JSON格式的字符串)
//        NSString *jsonString = [NSDictionary convertDictionaryToJson:@{@"test":@"123", @"data":@"666"}];
//        NSString *jsCallBack = [NSString stringWithFormat:@"(%@)(%@);", jsFunctionString, jsonString];
//        //执行回调
//        [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>

使用WKWebViewjs传值

OC代码如下

- (WKWebView *)wkWebView {
    if (!_wkWebView) {
        // 进行配置控制器
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        // 实例化对象
        configuration.userContentController = [WKUserContentController new];
        // 调用JS方法
        [configuration.userContentController addScriptMessageHandler:self name:@"NativeModel"];
        
        // 进行偏好设置
        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

- (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>

遇到的问题

上一篇下一篇

猜你喜欢

热点阅读