美文网首页
OC与JS间的交互

OC与JS间的交互

作者: 你飞跃俊杰 | 来源:发表于2023-12-05 10:50 被阅读0次

    OC

    //
    //  WebViewController.m
    //  Test
    //
    //  Created by lvfeijun on 2023/7/31.
    //
    
    #import "WebViewController.h"
    #import <WebKit/WebKit.h>
    #import <WebKit/WKWebView.h>
    #import <WebKit/WKUserContentController.h>
    
    @interface WebViewController ()<WKUIDelegate,UIWebViewDelegate,WKNavigationDelegate>
    
    @property (nonatomic ,strong) WKWebView *webView;
    @property (nonatomic ,strong) WKUserContentController *userContentController;
    
    @end
    
    @implementation WebViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        
        [self.view addSubview:self.webView];
        
        [self.webView addObserver:self forKeyPath:@"URL" options:NSKeyValueObservingOptionNew context:nil];
    }
    
    - (WKWebView *)webView
    {
        if(!_webView){
            //配置环境
            WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
        
    //        self.userContentController = [self createWKUserContentController];
    //        configuration.userContentController = self.userContentController;
            _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, 400, 800) configuration:configuration];
            NSString *webPath = [[NSBundle mainBundle] pathForResource:@"html"
                                                 ofType:@"html"];
            NSURL *webURL = [NSURL fileURLWithPath:webPath];
            _webView.UIDelegate = self;
            _webView.navigationDelegate = self;
            [_webView loadRequest:[NSURLRequest requestWithURL:webURL]];
        }
        return _webView;
    }
    
    -(WKUserContentController *)createWKUserContentController{
        WKUserContentController *userContentController =[[WKUserContentController alloc]init];
    //        //注册方法
        [userContentController addScriptMessageHandler:self  name:@"sayhello"];
        [userContentController addScriptMessageHandler:self  name:@"openGestureBack"];
        [userContentController addScriptMessageHandler:self  name:@"closeGestureBack"];
        return userContentController;
    }
    
    
    - (void)dealloc
    {
        
        [self.userContentController removeAllUserScripts];
        NSLog(@"removeAllUserScripts");
        [self.userContentController removeScriptMessageHandlerForName:@"sayhello"];
        NSLog(@"removeScriptMessageHandlerForName");
        
        
        @try {
            [self.webView removeObserver:self forKeyPath:@"URL"];
            NSLog(@"removeObserver  URL");
            
            [self.webView removeObserver:self forKeyPath:@"URL"];
            NSLog(@"removeObserver  URL");
            
            [self.webView removeObserver:self forKeyPath:@"URL"];
            NSLog(@"removeObserver  URL");
        } @catch (NSException *exception) {
            NSLog(@"@try crash %@",exception.reason);
        } @finally {
            
        }
    
    }
    
    -(void)closeGestureBack{
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        NSLog(@"closeGestureBack");
    }
    -(void)openGestureBack{
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        NSLog(@"openGestureBack");
    }
    
    - (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
        NSLog(@"message-》%@",message);
        if ([message.name isEqualToString:@"currentCookies"]) {
           
        }else if ([message.name isEqualToString:@"closeGestureBack"]){
            [self closeGestureBack];
        }else if ([message.name isEqualToString:@"openGestureBack"]){
            [self openGestureBack];
        }
    }
    
    #pragma mark - WKNavigationDelegate
    
    //! WKWeView在每次加载请求前会调用此方法来确认是否进行请求跳转
    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
        
        NSURL *url = navigationAction.request.URL;
        if ([url.scheme caseInsensitiveCompare:@"jsToOc"] == NSOrderedSame) {
            NSLog(@"absoluteString:%@",url.absoluteString);
            NSLog(@"relativeString:%@",url.relativeString);
    //        [WKWebViewInterceptController showAlertWithTitle:navigationAction.request.URL.host message:navigationAction.request.URL.query cancelHandler:nil];
            decisionHandler(WKNavigationActionPolicyCancel);
        }
        else {
            decisionHandler(WKNavigationActionPolicyAllow);
        }
    }
    
    - (void)viewDidDisappear:(BOOL)animated
    {
        [super viewDidDisappear:animated];
        
    //    [self.webView removeObserver:self forKeyPath:@"URL"];
    }
    
    /*
    #pragma mark - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */
    
    @end
    
    

    html

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title></title>
    </head>
    <body>
    
    //! 登录按钮
    <button onclick = "login()" style = "font-size: 18px;">登录</button>
    </p>
    
    <button onclick = "sayhello()" style = "font-size: 18px;">sayhello</button>
    
    <button onclick = "closeGestureBack()" style = "font-size: 18px;">closeGestureBack</button>
    
    <button onclick = "openGestureBack()" style = "font-size: 18px;">openGestureBack</button>
    
    //! 登录
    <script>
    function login() {
      var token = "js_tokenString";
      loginSucceed(token);
    }
        
        function closeGestureBack() {
            window.webkit.messageHandlers.closeGestureBack.postMessage({body: 'hello world!'});
        }
        
        function openGestureBack() {
            window.webkit.messageHandlers.openGestureBack.postMessage({body: 'hello world!'});
        }
    
        function sayhello() {
            window.webkit.messageHandlers.sayhello.postMessage({body: 'hello world!'});
        }
        
    //! 登录成功
    function loginSucceed(token) {
      var action = "loginSucceed";
      jsToOc(action, token);
    }
    
    //! JS调用OC入口
    function jsToOc(action, params) {
      var url = "jsToOc://" + action + "?" + params;
    <!--  loadURL(url);-->
        loadURL("jsToOc://sayhello");
    }
    
    //! 加载URL
    function loadURL(url) {
      window.location.href = url;
    }
    </script>
    </body>
    </html>>
    
    
    
    
    

    相关文章

      网友评论

          本文标题:OC与JS间的交互

          本文链接:https://www.haomeiwen.com/subject/pdqdgdtx.html