IOS WKWebView and ioswkwebview

Source: Internet
Author: User

IOS WKWebView and ioswkwebview

UIWebView is not required. This is outdated. We recommend that you use WKWebView in the future.

WKWebViewIt is the core of modern WebKit APIs in iOS 8 and OS X Yosemite applications. It replacesUIWebViewAnd AppKitWebViewProvides a unified cross-platform API.

It features a 60 FPS rolling update rate, built-in gestures, efficient app and web information exchange channels, and the same JavaScript Engine as Safari,WKWebViewIt is undoubtedly the highlight of WWDC 2014.

[Difference between UIWebView and WKWebView]
WKWebViewFaster (only 1/3 of UIWebView memory is occupied ~ 1/4), no cacheIn more detail, the methods in UIWebViewDelegate are split.

[Why is it time to migrate from UIWebView to WKWebView]
By the time I wrote this article, according to mixpanel data, iOS 9 had a share of 58.55%, iOS 8 had a share of 34.78%, and iOS 7 and earlier versions were 6.66%, most of the 6.66% users are those who use mobile phones extremely infrequently. So from now on, you can only develop apps compatible with iOS 8 and iOS 9 (if your product does not have strict coverage requirements ). WKWebView is only available in WebKit after iOS 8. Therefore, when we want to be compatible with both iOS 7 and iOS 8, we can say that it is too troublesome for UIWebView and WKWebView to work together, there is no reason to reject new things.

Current iOS versions of the market usage see: https://developer.apple.com/support/app-store/

[Common proxy methods]

In WKWebView, UIWebViewDelegate and UIWebView are reconstructed into 14 types and 3 protocols. The following describes the versions of WKWebView that are commonly used in UIWebView.

 

// Prepare to load the page UIWebViewDelegate-webView: shouldStartLoadWithRequest: Taobao-webView: Taobao: // the page has been loaded. You can add a transition animation UIWebViewDelegate-webViewDidStartLoad to the view in this step: transition-webView: didCommitNavigation: // the page has been fully loaded. You can remove the transition animation in this step. UIWebViewDelegate-Progress: WKNavigationDelegate-webView: didFinishNavigation: // The page fails to be loaded: didFailLoadWithError: WKNavigationDelegate-webView: didFailNavigation: withError: WKNavigationDelegate-webView: didFailProvisionalNavigation: withError:

  

The preceding methods exist in UIWebViewDelegate and WKNavigationDelegate respectively.
If you used only the methods listed above in UIWebViewDelegate, simply change the method name so that your ViewController can inherit WKNavigationDelegate and continue using it. If you want more information, you can click "WKNavigationDelegate" on the left of the cmd key + mouse to view it through Xcode.
Note thatwebview.delegate = selfTo be rewrittenwebview.navigationDelegate = self.

JS Interaction

In UIWebView, a simplewebView.stringByEvaluatingJavaScriptFromString()You can use JS scripts to manipulate WebView. In WKWebView, we may need to useWKScriptMessageHandlerIn this Protocolfunc userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)Method.

The following sample code is used to obtain the text in the webpage from WKWebView.

Let js = "window. webkit. messageHandlers. observe. postMessage (document. body. innerText); "// note that the observe field here is self-written, not a fixed writing method. For details, refer to the 6th line let script = WKUserScript (source: js, injectionTime: WKUserScriptInjectionTime. atDocumentEnd, forMainFrameOnly: true) // The AtDocumentEnd field here refers to the Javascript script inserted after the content in the webpage is loaded. You can also select AtDocumentStart, insert a script when document element is just created. let config = WKWebViewConfiguration () config. userConte NtController. addUserScript (script) config. userContentController. addScriptMessageHandler (self, name: "observe") // corresponds to the observe field in the first line of JS script // initialize WKWebView let webview = WKWebView (frame: CGRectMake (0, 0, self. view. frame. width, self. view. frame. height), configuration: config) webview. navigationDelegate = self. view. addSubview (webview) // load the web page webview. loadRequest (NSURLRequest (URL: NSURL (string: "http : // Www.jianshu.com ")!))

  


You may also notice that the way to inject JS scripts into WebView is to initialize a WebView, so you need to write your own script before WebView initialization. Of course, if you do not need JS interaction, you can use a frame to initialize WebView and remove the configuration parameter.

However, how do we get the text captured from WKWebView (via document. body. innerText )?
As mentioned above, let your ViewController inherit WKNavigationDelegate and then inherit WKScriptMessageHandler. Then implement the only method in WKScriptMessageHandler:

Func userContentController (userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {let str: NSString = message. body! NSString // because we captured the text, here we forcibly convert message. body to NSString. If you get other information through JS, convert print (str) as needed )}

  

At first glance, we may be confused: We bound WKWebView with WKNavigationDelegate, but WKScriptMessageHandler didn't provide a proxy method. In fact, the corresponding process appears in the 5th lines in the previous Code:config.userContentController.addScriptMessageHandlerThis sentence.

 
References: http://nshipster.cn/wkwebkit/http://www.jianshu.com/p/f94cad074196

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.