In the previous article, we used the JavaScriptCore framework to rewrite the previous example. iOS8 Apple prefers HTML5, refactored UIWebVIew, and brought us WKWebView, which greatly improved its performance, stability and functions, and better supported the new features of HTML5. In this article, we will use WKWebView to try it out
1. WKWebView Framework
WKWebView has 14 classes and 3 protocols:
WKBackForwardList: A list of web pages that have been visited before can be accessed through back and forward actions.
WKBackForwardListItem: A certain web page in the back list in the webview.
WKFrameInfo: Contains the layout information of a web page.
WKNavigation: Contains loading progress information of a web page.
WKNavigationAction: Contains information that may cause web page navigation to change, and is used to determine whether navigation changes are made.
WKNavigationResponse: Contains return content information that may cause web page navigation to change, and is used to determine whether navigation changes are made.
WKPreferences: Overview of the preferences of a webview.
WKProcessPool: Represents a web content loading pool.
WKUserContentController: Provides methods to use JavaScript post information and inject script.
WKScriptMessage: Contains information sent by a web page.
WKUserScript: Indicates a user script that can be accepted by the web page.
WKWebViewConfiguration: Initialize the settings of the webview.
WKWindowFeatures: Specifies the window properties when loading a new web page.
WKWebsiteDataStore: Contains web page data storage and search.
WKNavigationDelegate: provides relevant methods to track the web page loading process of the main window and determine whether the main window and child window are loading a new page.
WKUIDelegate: Provides a callback to display web pages using native controls.
WKScriptMessageHandler: Provides a callback method for receiving messages from a web page.
2. Three proxy methods in WKWebView
1. WKNavigationDelegate
The methods provided by this proxy can be used to track the loading process (page starts loading, loading completed, loading failed), and decide whether to perform jumps.
// Called when the page starts loading - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation; // Called when the content starts to return - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation; // Called after the page is loaded - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation; // Called when the page fails to load - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;
There are three types of proxy methods for page jumping, which are divided into (received jump and decide whether to jump)
// Called after receiving the server jump request - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation; // After receiving the response, decide whether to jump - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler; // Decide whether to jump before sending the request - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
2. WKUIDelegate
Create a new WKWebView
// Create a new WebView - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures;
The remaining three proxy methods are all related to the pop-up prompt box on the interface. The three prompt boxes (warning box, confirmation box, and input box) for the web interface correspond to three proxy methods.
// A warning box pops up on the interface - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(void (^)())completionHandler; // The confirmation box pops up on the interface - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler; // The input box pops up on the interface - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler;
3. WKScriptMessageHandler
This protocol contains a method that must be implemented. This method is the key to native interaction with the web. It can directly convert the received JS script into an OC or Swift object.
// Called when receiving a script from the web interface - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;
3. Rewrite using WKWebView
Here we have made some changes to the previous interface. When OC called JS, it used to pop-up frame processing. When I was writing here, I was very depressed that the method could be called in the past, but the call to the alert method of js has no effect, so here we use the output to the div and add a clear button.
WKWebView does not support nib files, so you need to use code to initialize and load the WebView.
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; = 18; = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, , /2) configuration:config]; [ addSubview:]; NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]; NSURL *baseURL = [[NSBundle mainBundle] bundleURL]; [ loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:baseURL];
OC side:
//1. JS calls OC to add processing scripts [userCC addScriptMessageHandler:self name:@"showMobile"]; [userCC addScriptMessageHandler:self name:@"showName"]; [userCC addScriptMessageHandler:self name:@"showSendMsg"]; // Handle corresponding events in the proxy method - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { NSLog(@"%@",NSStringFromSelector(_cmd)); NSLog(@"%@",); if ([ isEqualToString:@"showMobile"]) { [self showMsg:@"I am Xiaohong below. My mobile phone number is: 18870707070"]; } if ([ isEqualToString:@"showName"]) { NSString *info = [NSString stringWithFormat:@"Hello %@, I'm glad to see you",]; [self showMsg:info]; } if ([ isEqualToString:@"showSendMsg"]) { NSArray *array = ; NSString *info = [NSString stringWithFormat:@"This is my mobile number: %@, %@!!",,]; [self showMsg:info]; } } // 2. native call js - (IBAction)btnClick:(UIButton *)sender { if (!) { if ( == 123) { [ evaluateJavaScript:@"alertMobile()" completionHandler:^(id _Nullable response, NSError * _Nullable error) { //TODO NSLog(@"%@ %@",response,error); }]; } if ( == 234) { [ evaluateJavaScript:@"alertName('Little Red')" completionHandler:nil]; } if ( == 345) { [ evaluateJavaScript:@"alertSendMsg('18870707070','It's a great time to climb the mountain on the weekend')" completionHandler:nil]; } } else { NSLog(@"the view is currently loading content"); } }
JS side:
function clear() { ('mobile').innerHTML = '' ('name').innerHTML = '' ('msg').innerHTML = '' } // List of methods for OC calling JS function alertMobile() { //It has been called here, but I don't understand why the alert method does not respond //alert('I am Xiao Huang above. My mobile number is: 13300001111') ('mobile').innerHTML = 'I am Xiao Huang above. My mobile phone number is: 13300001111' } function alertName(msg) { //alert('Hello' + msg + ', I'm very happy to see you too') ('name').innerHTML = 'Hello ' + msg + ', I'm very happy to see you, too } function alertSendMsg(num,msg) { //('This is my mobile number:' + num + ',' + msg + '!!') ('msg').innerHTML = 'This is my mobile number:' + num + ',' + msg + '!!' } //JS response method list function btnClick1() { (null) } function btnClick2() { ('xiaohuang') } function btnClick3() { (['13300001111', 'Go Climbing This Weekend !!!']) }
4. Postscript
So far, the entire series of examples have been completed and the goods have been received in a lot of time. Each article will summarize the knowledge points and give the address of the example DEMO at the end of the article.
Example DEMO:OC-JS-WKWebView_jb51.rar
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.