需求:
  需要在手机端用WKWebView加载链接展示html,并且需要与html中按钮做交互
实现:

#import "ViewController.h"
#import <WebKit/WebKit.h>
@interface ViewController ()<WKScriptMessageHandler,WKNavigationDelegate>
@property(nonatomic,strong) WKWebView  *webView ;
@end
static NSString *strID = @"pullnewactive";
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.titleName;
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    //strID: H5界面的标识符
    WKUserContentController * wkUController = [[WKUserContentController alloc] init];
    [wkUController addScriptMessageHandler:self  name:strID];
    config.userContentController = wkUController;
    //创建WKWebView
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) configuration:config];
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    //加载url
    NSURL * baseUrl = [NSURL URLWithString:self.urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:baseUrl];
    [_webView loadRequest:request];
     //加载进度条
    _progressLayer = [WYWebProgressLayer new];
    _progressLayer.frame = CGRectMake(0, Navigationbar_Height, SCREEN_WIDTH, 2);
    [self.navigationController.navigationBar.layer addSublayer:_progressLayer];
}
#pragma mark  ------------ WKScriptMessageHandler --------
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
  // NSDictionary * parameter = message.body;  如果带参数可以从parameter获取
    if([message.name isEqualToString:strID]){//点击按钮执行的方法
       
    }
}
#pragma mark ------------ WKNavigationDelegate ------------
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"正在加载");
    [_progressLayer startLoad];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    [_progressLayer finishedLoad];
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"返回内容了");
}
//页面加载完成以后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"页面加载完成以后调用");
    //禁止保存图片
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'" completionHandler:nil];
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'" completionHandler:nil];
    [_progressLayer finishedLoad];
}



//移除注册的js方法(注意需要移除)
-(void)dealloc{
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:strID];
}
//如果H5界面有电话需要添加,拨打电话时调用
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    if ([scheme isEqualToString:@"tel"]) {
        NSString *resourceSpecifier = [URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", resourceSpecifier];
        /// 防止iOS 10及其之后,拨打电话系统弹出框延迟出现
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        });
    }
 decisionHandler(WKNavigationActionPolicyAllow);
}

HTML中需要在按钮点击事件中实现:


// additives 自定义参数
 if(appMessage()==='Android'){
        
       window.additives.payAction()

   }else if(appMessage()==='IOS'){

        window.webkit.messageHandlers.additives.postMessage({});

        //window.webkit.messageHandlers.additives.postMessage({"params":"我是参数"});

   }


//判断是iOS 还是安卓的方法
function appMessage() {
     var u = navigator.userAgent,
     app = navigator.appVersion;
     var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;             
     //android终端或者uc浏览器
     var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
     var appType = "";
     if (isAndroid) {
         appType = "Android";
     } else if (isiOS) {
         appType = "IOS";
     }
     return appType;
 }

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐