How Swift uses Wkwebview to invoke the Web in an iOS app

Source: Internet
Author: User

This article focuses on Swift's approach to using Wkwebview to invoke the Web in iOS apps, and using Wkwebview is tantamount to using the same JavaScript interpreter as in Safari to replace the UIWebView of the past. A friend you need can refer to the following

Since IOS8 began, Apple has introduced Wkwebview to replace UIWebView. In contrast, Wkwebview consumes less and features more power. Let's take a look at Wkwebview how to use it!

0. Initialization
(1) First need to introduce WebKit library

Copy CodeThe code is as follows:
#import <WebKit/WebKit.h>
(2) The method of initialization is divided into the following two
Copy CodeThe code is as follows:
Default initialization
-(Instancetype) initWithFrame: (CGRect) frame;
Initialization based on the configuration of the WebView
-(Instancetype) initWithFrame: (CGRect) frame configuration: (Wkwebviewconfiguration *) configuration Ns_designated_ INITIALIZER;
(3) Load the Web page and HTML code the same way as UIWebView, the code is as follows:
Copy CodeThe code is as follows:
Wkwebview *webview = [[Wkwebview alloc] initWithFrame:self.view.bounds];
[WebView loadrequest:[nsurlrequest requestwithurl:[nsurl urlwithstring:@ "http://www.baidu.com"]];
[Self.view Addsubview:webview];

1. Proxy method for Wkwebview
(1) wknavigationdelegate
The agent provides methods that can be used to track the loading process (the page starts loading, loading is complete, loading fails), and deciding whether to perform a jump.

Copy CodeThe code is as follows:
Called when the page starts to load
-(void) WebView: (Wkwebview *) WebView didstartprovisionalnavigation: (wknavigation *) navigation;
Called when the content starts to return
-(void) WebView: (Wkwebview *) WebView didcommitnavigation: (wknavigation *) navigation;
Called after page load is complete
-(void) WebView: (Wkwebview *) WebView didfinishnavigation: (wknavigation *) navigation;
Called when a page load fails
-(void) WebView: (Wkwebview *) WebView didfailprovisionalnavigation: (wknavigation *) navigation;
Page Jump Agent method has three kinds, divided into (received jump and decide whether to jump two)
Copy CodeThe code is as follows:
Called after a server jump request has been received
-(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;
Before sending a request, decide whether to jump
-(void) WebView: (Wkwebview *) WebView decidepolicyfornavigationaction: (wknavigationaction *) navigationaction Decisionhandler: (void (^) (wknavigationactionpolicy)) Decisionhandler;
(2) Wkuidelegate
Copy CodeThe code is as follows:
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 interface pop-up prompt box, for the Web interface three kinds of prompt boxes (warning box, confirmation box, input box) corresponding to three proxy methods. Here are just a few examples of warning boxes.
Copy CodeThe code is as follows:
/**
* Called when there is a popup warning box in the Web interface
*
* @param WebView Implement the agent's WebView
* @param the contents of the Message warning box
* @param frame Main window
* @param completionhandler warning Box disappears call
*/
-(void) WebView: (Wkwebview *) WebView runjavascriptalertpanelwithmessage: (NSString *) message initiatedbyframe: (void ( ^) ()) Completionhandler;
(3) Wkscriptmessagehandler
This protocol contains a method that must be implemented, which is the key to improving the interaction between the app and the Web, and it can convert the received JS script directly to the OC or Swift object. (Of course, UIWebView can also interact with the web through the "curve salvation" approach, which is the famous Cordova framework)
Copy CodeThe code is as follows:
Called when a script is received from the Web interface
-(void) Usercontentcontroller: (Wkusercontentcontroller *) Usercontentcontroller didreceivescriptmessage: ( Wkscriptmessage *) message;

2. Modify Info.plist
Note Starting from IOS9, all involved in the network operation, should be added in the Info.plist:

3. Loading Web pages
To import WebKit in Viewcontroller first:

Copy CodeThe code is as follows:
Import WebKit
And then:
Copy CodeThe code is as follows:
var webview = Wkwebview ()
Override Func Viewdidload () {
Super.viewdidload ()
Create Wkwebview
Let WebView = Wkwebview (frame:cgrectmake (0, 0, self.view.frame.width, self.view.frame.height))
Create URLs
Let URL = Nsurl (string: "Http://www.jianshu.com/users/040395b7230c/latest_articles")
Create request
Let request = Nsurlrequest (url:url!)
Load Request
Webview.loadrequest (Request)
Add Wkwebview
Self.view.addSubview (WebView)
}
Operating effect:

4. Get the page title
In order to display the title, first embed a navigationcontroller for Viewcontroller. With the navigation bar, we need to adjust the y-axis position of the webview to prevent the navigation bar from obscuring the upper part of the page and writing it in Viewdidload ():

Copy CodeThe code is as follows:
Get navigation bar Height
Let Navheight = Self.navigationcontroller?. NavigationBar.frame.height
Get status bar height
Let Statusheight = Uiapplication.sharedapplication (). statusbarframe.height
WebView = Wkwebview (Frame:cgrectmake (0, Statusheight+navheight!,self.view.frame.width, self.view.frame.height))
Second, the wknavigationdelegate is used here, so in Viewdidload () add
Copy CodeThe code is as follows:
Self.webview.navigationDelegate = Self
Note that the page title to be available after the page is loaded, otherwise it is empty, so we use the ' handle page loading complete ' method:
Copy CodeThe code is as follows:
Func WebView (Webview:wkwebview, didfinishnavigation navigation:wknavigation!) {
Self.navigationItem.title = Self.webview.title
}
Operating effect:

5. Forward and backward
First we'll add the forward and Back buttons on the Navgationbar:

Copy CodeThe code is as follows:
var btnback = Uibarbuttonitem ()
var btnforward = Uibarbuttonitem ()
Func Setnavbar () {
Btnback = Uibarbuttonitem (title: "Back", Style:UIBarButtonItemStyle.Plain, target:self, Action: "Toback")
Btnforward = Uibarbuttonitem (title: "Forward", Style:UIBarButtonItemStyle.Plain, target:self, Action: "Toforward")
Self.navigationItem.leftBarButtonItem = Btnback
Self.navigationItem.rightBarButtonItem = Btnforward
}
Then we use the GoBack () and GoForward () methods, before we go forward or backward, we need to determine whether the webpage can move forward or backward:
Copy CodeThe code is as follows:
Func Toback () {
If Self.webview.canGoBack {
Self.webview.goBack ()
}
}

Func Toforward () {
If Self.webview.canGoForward {
Self.webview.goForward ()
}
}


Finally add a call to the Setnavbar () method in Viewdidload ():
Copy CodeThe code is as follows:
Setnavbar ()
Operating effect:

6. Modify the page configuration
Now, a seemingly simple browser is done, but if we replace the URL with:
Http://csol2.tiancity.com/homepage/article/Class_1166_Time_1.html
Change in Viewdidload ():

Copy CodeThe code is as follows:
Let URL = Nsurl (string: "http://csol2.tiancity.com/homepage/article/Class_1166_Time_1.html")
We will find the text on the list on the page, including the text clicked on the top bar did not respond, the problem is where? This is because the system is blocking unsecured connections. How to solve it? We're going to use the Createwebviewwithconfiguration () method in Wkuidelegate to allow navigation, first we'll set up our own proxies and add them in Viewdidload ():
Copy CodeThe code is as follows:
Self.webview.UIDelegate = Self
Secondly:
Copy CodeThe code is as follows:
Func WebView (Webview:wkwebview, Createwebviewwithconfiguration configuration:wkwebviewconfiguration, Fornavigationaction navigationaction:wknavigationaction, windowfeatures:wkwindowfeatures), WKWebView? {
Allow navigation if the target main view is not empty
if! (Navigationaction.targetframe?). MainFrame! = nil) {
Self.webview.loadRequest (Navigationaction.request)
}
return Nil
}
Run it and find the click Jump!

7. Handle JS's Prompt box
Now change the website to

http://evt.tiancity.com/csol2/1565/home/index.php
Change in Viewdidload ():

Copy CodeThe code is as follows:
Let URL = Nsurl (string: "http://evt.tiancity.com/csol2/1565/home/index.php")
Pull down, click on ' Collect now ', should appear the prompt box, but found nothing happened. To do this, we have to deal with JS's cue box event. Remember the method you mentioned at the beginning, as follows:
Copy CodeThe code is as follows:
Func WebView (Webview:wkwebview, Runjavascriptalertpanelwithmessage message:string, initiatedbyframe frame: Wkframeinfo, Completionhandler: (), Void) {
Let alert = Uialertcontroller (Title:nil, Message:message, Preferredstyle:. Alert)
Alert.addaction (uialertaction (title: "OK", Style:.) Default, Handler: {(_), Void in
Completionhandler ()
}))
Self.presentviewcontroller (Alert, animated:true, Completion:nil)
}
Here to create a warning box to display, and now run a look?!

8. Add a progress bar
We know that UIWebView is unable to get the progress of the Web page loading, so we can not create a progress bar, of course, we could use some kind of algorithm to simulate the page load, set the value of the progress bar itself. Wkwebview, however, provides a way to get web page loading progress, supporting KVO, which is estimatedprogress. There are also loading are loading and title page titles.
We have to create a progress bar:

Copy CodeThe code is as follows:
var Progbar = Uiprogressview ()
The following code is added to the Viewdidload ()
Progbar = Uiprogressview (frame:cgrectmake (0, 0, Self.view.frame.width, 30))
progbar.progress = 0.0
Progbar.tintcolor = Uicolor.redcolor ()
Self.webview.addSubview (Progbar)
Then add listening progress to the page, also in Viewdidload ():
Copy CodeThe code is as follows:
Self.webview.addObserver (Self, Forkeypath: "Estimatedprogress", Options:NSKeyValueObservingOptions.New, Context: Nil
Re-processing KVO:
Copy CodeThe code is as follows:
Override Func Observevalueforkeypath (keypath:string, Ofobject object:anyobject?, change: [String:anyobject]?, Contex t:unsafemutablepointer<void>) {
if KeyPath = = "Estimatedprogress" {
Self.progBar.alpha = 1.0
Progbar.setprogress (Float (webview.estimatedprogress), animated:true)
The maximum value of the progress bar is 1.0
if (self.webview.estimatedProgress >= 1.0) {
Uiview.animatewithduration (0.3, delay:0.1, Options:UIViewAnimationOptions.CurveEaseInOut, animations: {() Void Inch
Self.progBar.alpha = 0.0
}, Completion: {(Finished:bool), Void in
self.progBar.progress = 0
})
}
}
}
It is important to set the value of the progress bar here, because we find that the value of the progress bar is always slower than the actual value of the page load, and the two are not synchronized. If you don't add an animation to make the progress bar load and disappear, you'll see that the progress bar is not halfway to the right. So we're going to use an animation to make it work. In addition, if the self.progBar.progress = 0 sentence, that is, the function of zeroing into other methods, for example, to start the navigation when the zero, you will find the progress bar animation problems, will come back. In short, how to deal with the animation of the progress bar is very particular, I have tried several times to find that this method is relatively stable. So I suggest you can change the style of the progress bar, that is, does not depend on the value of the display, such as can be turned round and so on. Now there are a lot of third-party libraries can be used, you can go to Cocoapods to find.

Also do not forget, for KVO mode, have add must remove, otherwise it will crash. We can add a remove when the view disappears:

Copy CodeThe code is as follows:
Override func Viewwilldisappear (Animated:bool) {
Webview.removeobserver (Self, Forkeypath: "Estimatedprogress")
}

You can change some of the Web site to try!

9. Ultimately

10. Summary
The simple use of Wkwebview is introduced here! People are interested in adding more features to it! If you like this article, don't forget to click like Oh!

Postscript
Since we say that Wkwebview consumes less memory than UIWebView, let's actually compare them, we let them load the same site, and the results
(Left is UIWebView, right is Wkwebview):

How Swift uses Wkwebview to invoke the Web in an iOS app

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.