Interaction between iOS and H5 [WKWebView]

H5 because of its timely response to the update speed comparable to the speed of demand and high interest by more and more users of all ages. Currently, most applications are embedded in H5. Very obvious advantages. So how to embed a H5 in the iOS application, and interact with it has become a potential need to master the technology. In this paper, I will combine some of the needs of the project in order to sort out the corresponding technical points for reference only.

In iOS development, H5 can be embedded by UIWebView or WKWebView. These two are inherited UIView, to load the class of web data. UIWebView was started in iOS2. Characterized by slow loading speed, memory, and more difficult to optimize. WKWebView is a new apple in the iOS8, loading speed, less memory, is a good choice. If you want to compare the difference between the two, you can choose a web page for testing. As mentioned above, we choose WKWebView for development. All right, no more bullshit.

1.WKWebView create and load

- (void) createWebView *config [[WKWebViewConfiguration alloc] {WKWebViewConfiguration = init] / / according to need to set up the corresponding properties of the WKWebView *webView [[WKWebView alloc]initWithFrame:self.view.bounds = configuration:config]; webView.navigationDelegate = self; [self.view addSubview:webView]; NSURL *url = [NSURL URLWithString:self.strURL]; [self loadWebViewWithURL:url]; / / JS OC [self.webView.configuration.userContentController addScriptMessageHandler:self script call add name:@ "Share"];}

2.JS call OC code.

[self.webView.configuration.userContentController addScriptMessageHandler:self name:@ "Share"];

This is the use of a new feature MessageHandler WKWebView to deal with the JS call native methods. To achieve the JS call iOS native method, step down.

  • Add < WKScriptMessageHandler> protocol. Make the controller a proxy object for MessageHandler.
  • The name of the method to monitor and JS developers to discuss. Here we are listening to the Share method, for JS developers must be written in the following ways. Window.webkit.messageHandlers. Share.postMessage (null)
  • Protocol implementation method. In this method, the message parameter has an attribute body. Message.body is passed over the parameters of JS, can be a string, can be an array, can also be a dictionary. Judging by message.name can know what is the method of monitoring JS.
- (void) userContentController: (WKUserContentController * userContentController) didReceiveScriptMessage: (WKScriptMessage * message) {if ([message.name isEqualToString:@ "Share"]) {//TODO}}

So far, JS call OC code is over. Is not very simple. In addition, I also see a different way of processing on the internet. We can refer to WebViewJavascriptBridge I think it is more clear. I have not tried this, if you have tried the baby can not share the advantages and disadvantages of both ah.

3 OC call JS code.

[self.webView evaluateJavaScript:@ (show) completionHandler:^ (ID _Nullable response NSError * _Nullable error) {//TODO}];

I believe the code has been very clear. Show () is written in JS method, this method can be passed without passing parameters, depending on the actual situation. In addition, the interaction between UIWebView and JS, the following part is for reference only.

JSContext *context [self.webView valueForKeyPath:@ = "documentView.webView.mainFrame.javaScriptContext"]; context[@ "Share"] = ^ () {NSArray *args = [JSContext currentArguments]; dispatch_async (dispatch_get_main_queue), ^{} (//TODO);

4 about < WKNavigationDelegate>

Web page loading start, end, the failure of these are particularly simple, I will not repeat. Say the following protocol method, this method occurs in the page jump. WKNavigationActionPolicy is an enumeration, WKNavigationActionPolicyAllow allows the jump, WKNavigationActionPolicyCancel said to cancel the jump. Yes, there is a supplement: scrollView nested web pages and native view, native view according to the height of the page layout. I see a lot of electricity supplier applications have this layout, but in the calculation of the height will have a variety of problems, I do not know you have met?

- (void) webView: (WKWebView * webView) decidePolicyForNavigationAction: (WKNavigationAction * navigationAction) (decisionHandler: (void ^) decisionHandler NSString (WKNavigationActionPolicy)) {*url = navigationAction.request.URL.absoluteString; if ([url! IsEqualToString:self.strURL]) {decisionHandler} / / page (WKNavigationActionPolicyAllow);}

5 about < WKUIDelegate >

Do not know if you have not met the JS written alert () box does not pop up on the iOS. Do you have any way to implement these protocols?.

Just create a new WebView - (WKWebView) webView: (WKWebView * webView) createWebViewWithConfiguration: (WKWebViewConfiguration * configuration) forNavigationAction: (WKNavigationAction * navigationAction) windowFeatures: (WKWindowFeatures * windowFeatures); / / / input box - (void) webView: (WKWebView * webView) runJavaScriptTextInputPanelWithPrompt: (NSString *) prompt defaultText: (nullable NSString * defaultText initiatedByFrame:) (WKFrameInfo * frame) (completionHandler: (void ^ (NSString) __nullable * result) completionHandler); / / / confirm box - (void) webView: (WKWebView * webView) runJavaScriptConfirmPanelWithMessage: (NSString * message) initiatedByFrame: (WKFrameInfo * frame) (completionHandler: (void ^ (BOOL) result) completionHandler); / / / (VOI - warning box D) webView: (WKWebView *) webView runJavaScriptAlertPanelWithMessage: (NSString *) message initiatedByFrame: (WKFrameInfo *) frame completionHandler: (void (^) (void)) completionHandler;

6 get the page title, page loading progress and loading status

This is the way to monitor the KVO. You can click on the inside of the WKWebView look at each of them have a long explanation of each attribute, you can not find this section. Give an example of getting the title. Other similar. Do not forget, KVO listener listener in the dealloc to remove oh.

Interaction between iOS and H5 [WKWebView]
8E6F0A58-609E-4093-BD65-F51A10D1703D.png
[self.webView addObserver:self forKeyPath:@ "title" options:NSKeyValueObservingOptionNew context:NULL];
- (void) observeValueForKeyPath: (NSString *) keyPath ofObject: (ID) object (change: NSDictionary< NSString id> * *, change) context: (void * context) {if ([keyPath isEqualToString:@ "title"]) {if (object = = self.webView) {if (self.navigationController) self.navigationItem.title = self.webView.title;} else {[super} observeValueForKeyPath:keyPath ofObject:object change:change context:context];}}

Above is my personal understanding of WKWebView. Demo is not on, and the server to cooperate. Because I wrote the basic H5 can not see people, ha ha, I will work hard!