关于WKWebView 1.原生传值到html; 2.监听ht

2019-07-25  本文已影响0人  91阿生
1. 原生传值到html:
 - (WKWebView *)webView {
    if (!_webView) {
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:self.webViewConfiguration];
        _webView.navigationDelegate = self;
    }
    return _webView;
 } 

- (WKWebViewConfiguration *)webViewConfiguration {
    if (!_webViewConfiguration) {
        _webViewConfiguration = [[WKWebViewConfiguration alloc] init];
        
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        preferences.javaScriptEnabled = YES;
        _webViewConfiguration.preferences = preferences;
        
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        _webViewConfiguration.userContentController = userContentController;
    }
    return _webViewConfiguration;
}
可利用WKUIDelegate协议监听
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemAdd) target:self action:@selector(add)];

- (void)add {
    NSString *str = [NSString stringWithFormat:@"testabc('%@')", @"哈哈 iOS测试传值->HTML"];
    [self.webView evaluateJavaScript:str completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"result=%@  error=%@",result, error);
    }];
}
5问题.png
解决:
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf8">
        <script language="javascript">
            // js传参数
            function paramClick() {
                var content = document.getElementById("firstid").value;
                window.webkit.messageHandlers.Param.postMessage({first:'来自js的数据:',second:content});
            }
            // 展示oc所传js数据
            function transferPrama(param) {
                asyncAlert(str);//响应WKUIDelegate的代理方法runJavaScriptAlertPanelWithMessage
                document.getElementById("secondid").value = param;
            }
           // 延迟执行
            function asyncAlert(content) {
                setTimeout(function() {
                   alert(content);
                }, 1);
            }       
         </script>
    </head>
2.监听html函数
// 切记移除name: 
[self.webViewConfiguration.userContentController removeScriptMessageHandlerForName:@"xxx"];
// 添加注册
[self.webViewConfiguration.userContentController addScriptMessageHandler:self name:@"xxx"];

// 实现协议
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSString *name = message.name;
    NSString *appName = [NSBundle mainBundle].infoDictionary[@"CFBundleDisplayName"];
    
    // 转换模型
    SCScriptMessageModel *spModel = [SCScriptMessageModel mj_objectWithKeyValues:message.body];
    
    if ([name isEqualToString:kMobile]) { // 联系电话
        NSString *phoneString = [NSString stringWithFormat:@"telprompt://%@", spModel.mobile];
        /// 防止iOS 10及其之后,拨打电话系统弹出框延迟出现
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
            /// 10及其以上系统
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneString] options:@{} completionHandler:nil];
        } else {
            /// 10以下系统
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneString]];
        }
    } else if ([name isEqualToString:kNavigation]) {
        /// 显示sheet
        ACActionSheet *sheet = [[ACActionSheet alloc] initWithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:self.navigationNames actionSheetBlock:^(NSInteger buttonIndex) {
            if (self.navigationNames.count == buttonIndex) return;
            
            if ([self.navigationNames[buttonIndex] isEqualToString:kGaoDeName]) {
                if (SCMapCanOpenURL(kGaoDeMap)) {
                    // 经纬转换
                    NSDictionary *res = SCBaiDuTransformGaoDe(spModel.lat, spModel.lng);
                    NSString *latString = [res[@"lat"] stringValue];
                    NSString *lngString = [res[@"lng"] stringValue];
                    
                    NSString *urlSting =[[NSString stringWithFormat:@"iosamap://path?sourceApplication=%@&sid=BGVIS1&did=BGVIS2&dlat=%@&dlon=%@&dname=%@&dev=0&t=0",appName, latString, lngString, spModel.navPosition] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    [[UIApplication  sharedApplication] openURL:[NSURL URLWithString:urlSting]];
                } else {
                    NSString *alterString = [NSString stringWithFormat:@"暂未安装%@", kGaoDeName];
                    [SVProgressHUD showInfoWithStatus:alterString];
                }
            } else if ([self.navigationNames[buttonIndex] isEqualToString:kBaiDuName]) {
                if (SCMapCanOpenURL(kBaiDuMap)) {
                    NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?destination=name:%@|latlng:%@,%@&mode=driving&coord_type=bd09ll", spModel.navPosition, spModel.lat, spModel.lng] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    [[UIApplication  sharedApplication]openURL:[NSURL URLWithString:urlString]];
                } else {
                    NSString *alterString = [NSString stringWithFormat:@"暂未安装%@", kBaiDuName];
                    [SVProgressHUD showInfoWithStatus:alterString];
                }
            } else { //使用自带地图导航 苹果自带地图(不需要检测,所以不需要URL Scheme)
                // 当前位置
                MKMapItem *currentLocation =[MKMapItem mapItemForCurrentLocation];
                // 设置终点坐标
                CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([spModel.lat doubleValue], [spModel.lng doubleValue]);
                MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coordinate]];
                toLocation.name = spModel.navPosition;
                // openMap
                [MKMapItem openMapsWithItems:@[currentLocation, toLocation] launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];
            }
        }];
        [sheet show];
    }
}
3.应用内调地图

百度地图官方网址: http://lbsyun.baidu.com/index.php?title=uri/api/ios
高德地图官方网址:https://lbs.amap.com/api/amap-mobile/guide/ios/navi/

上一篇下一篇

猜你喜欢

热点阅读