OC與JS間的交互

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>>




?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容