ios WKWebView和js交互

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

  • wkWebView懒加载
- (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 ()

//webView
@property (nonatomic, strong) WKWebView *wkWebView;

@end

  • 实现WKScriptMessageHandler代理方法,并在该代理方法中根据相应的注入js的名称,实现对应的逻辑
- (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);
//            }
//        }];
    }
}

前端代码如下




    
    html5page-oc

    








使用WKWebViewjs传值

OC代码如下

  • wkWebView懒加载
- (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 ()

//webView
@property (nonatomic, strong) WKWebView *wkWebView;

@end

  • 实现代理方法,在协议加载完WebView后,注入相应的js,将需要上传的参数上传给前端
- (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;
    
}

前端代码如下




    
    
    
    Document



    
新方法

遇到的问题

  • 上传参数到前端,注入js时出现Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={NSLocalizedDescription=A JavaScript exception occurred错误,检查上传的JSON是否正确,保证上传的JSON是一个正确的JSON即可

你可能感兴趣的:(ios WKWebView和js交互)