iOS wkwebview JS and OC call each other to transfer data

Foreword:
WKWebView is a view that displays interactive web content and supports iOS8.0 and macOS10.10 and above systems. Provides components to replace UIWebView . WKWebView solves the problems of slow loading of UIWebView , large memory usage, and difficulty in optimization. It can be said that WKWebView is the best choice for loading web pages inside App.

 

table of Contents

1. JS and OC interaction

 2. OC passes value to JS


1. JS and OC interaction

Add a method to inject JS

//Register a js method with a name of jsToOcNoPrams to set the object that processes the receiving JS method
[wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"JSToOcNoPrams"];

 [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"JSToOcWithPrams"];

JS side code example

<!--        JS语法-->
    <script type = "text/javascript">
        
    function JSToOcFunction1()
    {
       window.webkit.messageHandlers.JSToOcNoPrams.postMessage({});
    }
    
    function JSToOcFunction2()
    {
        window.webkit.messageHandlers.JSToOcWithPrams.postMessage({"params":"我是参数"});
    }

Lazy loading generates a webView

- (WKWebView *)webView {
    if (_webView == nil) {
        _userContentController = [[WKUserContentController alloc] init];
        
        _config = [[WKWebViewConfiguration alloc]init];
        _config.userContentController = _userContentController;
        _config.allowsInlineMediaPlayback = YES;
        
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        preferences.minimumFontSize = 12.0;
	 _config.preferences = preferences;

			 //这个类主要用来做native与JavaScript的交互管理
		 WKUserContentController * wkUController = [[WKUserContentController alloc] init];
			 //注册一个name为jsToOcNoPrams的js方法 设置处理接收JS方法的对象
		 [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"jsToOcNoPrams"];
		 [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"jsToOcWithPrams"];

		 _config.userContentController = wkUController;

		 _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:_config];
		 _webView.UIDelegate = self;
		 _webView.navigationDelegate = self;
		//_webView.opaque = NO;
		 _webView.backgroundColor = [UIColor whiteColor];
		_webView.allowsBackForwardNavigationGestures = YES;/// 是否允许手势左滑返回上一级, 类似导航控制的左滑返回
		// 设置没有弹性
		_webView.scrollView.bounces = NO;

    }
    return _webView;
}

The proxy method gets the JS data

#pragma mark - WKScriptMessageHandler
//实现js注入方法的协议方法
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {

    NSLog(@"JS方法名:%@", message.name);
    NSLog(@"JS参数:%@", message.body);
    //找到对应js端的方法名,获取messge.body
    if ([message.name isEqualToString:@"JSToOcNoPrams"]) {

    // 根据传过来的值处理逻辑、跳转页面等等
    HikRealplayViewController *vc = [[HikRealplayViewController alloc]init];
	vc.title = message.body[@"title"];
	[self.navigationController pushViewController:vc animated:YES];
    
       
    }
}

 2. OC passes value to JS

#pragma mark - WKNavigationDelegate

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载结束");

	NSString *jsStr = [NSString stringWithFormat:@"ocSetDeviceCode('%@')",[ZJPNetWork getUUID]];

	[self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
		NSLog(@"%@--%@",result,error);
	}];
}

@"ocSetDeviceCode('%@')",[ZJPNetWork getUUID]],  ocSetDeviceCode is the method name, ('%@') indicates the parameter

2. JS side obtains the implementation example of the passed value code

    function ocSetDeviceCode(value){            // Here js receives the value      }

Guess you like

Origin blog.csdn.net/zjpjay/article/details/103310279