iOS之webView与JS交互篇

WKWebView与OC交互

2017-06-09  本文已影响5人  f2efa87f6528

加载本地H5

//设置wk配置项
    WKWebViewConfiguration *Configuration = [[WKWebViewConfiguration  alloc]init];
    WKPreferences *Preferences = [[WKPreferences  alloc]init];
    Preferences.minimumFontSize = 40.0;
    Preferences.javaScriptEnabled = YES;
    Preferences.javaScriptCanOpenWindowsAutomatically = YES;
    Configuration.preferences = Preferences;
    
    //获取本地H5
    NSString *fileUrl = [[NSBundle mainBundle]pathForResource:@"index.html" ofType:nil];
    NSURL *url = [NSURL fileURLWithPath:fileUrl];
    
    //创建wkWebView
    self.wkWebView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:Configuration];
    [self.wkWebView loadFileURL:url allowingReadAccessToURL:url];
    self.wkWebView.UIDelegate = self;
    self.wkWebView.navigationDelegate = self;
    [self.view addSubview:self.wkWebView];
    
    //监听progress loading title 三个属性
    [self.wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.wkWebView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
    
     [self.wkWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
    
    //设置progress
    self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 2)];
    self.progressView.progressTintColor = [UIColor redColor];
    self.progressView.trackTintColor = [UIColor clearColor];
    [self.view insertSubview:self.progressView aboveSubview:self.wkWebView];

设置useContent

//设置userContent 按钮方法与H5一一对应
    [self.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"ScanAction"];
    [self.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"Location"];
    [self.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"Share"];
    [self.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"Color"];
    [self.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"Pays"];
    [self.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"Shake"];
    [self.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"GoBack"];
    [self.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"PlaySound"];

对应H5方法
  function payClick() {
                window.webkit.messageHandlers.Pays.postMessage({order_no:'201511120981234',channel:'wx',amount:1,subject:'粉色外套'});
            }

WKScriptMessageHandler代理方法 js调用oc

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if ([message.name isEqualToString:@"ScanAction"]) {
        [self HandleScanAction];
    }
    
}

oc注入js代码 setLocation()为H5方法名

- (void)HandleScanAction
{
    NSString *jsStr = [NSString stringWithFormat:@"setLocation('%@')",@"华为科技有限公司李小云"];
    [self.wkWebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
        NSLog(@"我调用完了");
        
    }];
    
}

kvo监听方法

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    
    if ([object isKindOfClass:[WKWebView class]] && [keyPath isEqualToString:@"estimatedProgress"]) {
        
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1 ) {
            [self.progressView setProgress:1.0 animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.hidden = YES;
            });
        }else{
          
            [UIView animateWithDuration:5 animations:^{
                 self.progressView.hidden = NO;
                [self.progressView setProgress:newprogress animated:YES];
            }];
            
        }
    }else if([object isKindOfClass:[WKWebView class]] && [keyPath isEqualToString:@"loading"])
    {
        
        NSLog(@"%@",@"loading");
        
    }else if([keyPath isEqualToString:@"title"]){
        
        self.title = self.wkWebView.title;
    }
    
    //已经加载完毕了
    if (!self.wkWebView.isLoading) {
        NSString *jsStr = [NSString stringWithFormat:@"callJsAlert()"];
        
        [self.wkWebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable reslut, NSError * _Nullable error) {
            
            NSLog(@"H5加载完毕");
            
        }];
    }
    
}

本文基本思路来自http://www.jianshu.com/p/6ba2507445e4

上一篇下一篇

猜你喜欢

热点阅读