Swift uses Wkwebview to invoke the Web in iOS applications _swift

Source: Internet
Author: User


Since IOS8 began, Apple has introduced Wkwebview to replace UIWebView. In comparison, Wkwebview consumes less and functions more powerfully. Let's see how wkwebview use it!



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


 code as follows:

#import <WebKit/WebKit.h>



(2) The initialization method is divided into the following two kinds


 code as follows:

Default initialization
-(Instancetype) initWithFrame: (CGRect) frame;
Initialize based on the configuration associated with the WebView
-(Instancetype) initWithFrame: (CGRect) frame configuration: (Wkwebviewconfiguration *) configuration Ns_designated_ initializer;



(3) Loading Web pages and HTML code in the same way as UIWebView, the code is as follows:


 code 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. Agent Method of Wkwebview
(1) wknavigationdelegate
The method provided by this agent can be used to track the loading process (the page starts loading, loading completed, loading failed), and decides whether to perform a jump.


 code as follows:

Called when the page starts to load
-(void) WebView: (Wkwebview *) WebView didstartprovisionalnavigation: (wknavigation *) navigation;
Called when the content begins to return
-(void) WebView: (Wkwebview *) WebView didcommitnavigation: (wknavigation *) navigation;
Called after page loading completes
-(void) WebView: (Wkwebview *) WebView didfinishnavigation: (wknavigation *) navigation;
Called when a page load fails
-(void) WebView: (Wkwebview *) WebView didfailprovisionalnavigation: (wknavigation *) navigation;



Page Jump Proxy method has three kinds, divides into (receives jumps and decides whether jumps two kinds)


code as follows:

Called after a server jump request is received
-(void) WebView: (Wkwebview *) WebView didreceiveserverredirectforprovisionalnavigation: (wknavigation *) navigation;
When a response is received, decide whether to jump
-(void) WebView: (Wkwebview *) WebView decidepolicyfornavigationresponse: (Wknavigationresponse *) navigationResponse Decisionhandler: (void (^) (wknavigationresponsepolicy)) Decisionhandler;
Before you send the request, decide whether to jump
-(void) WebView: (Wkwebview *) WebView decidepolicyfornavigationaction: (wknavigationaction *) navigationaction Decisionhandler: (void (^) (wknavigationactionpolicy)) Decisionhandler;



(2) Wkuidelegate


code as follows:

Create a new WebView
-(Wkwebview *) WebView: (Wkwebview *) WebView createwebviewwithconfiguration: (wkwebviewconfiguration *) configuration Fornavigationaction: (wknavigationaction *) navigationaction windowfeatures: (Wkwindowfeatures *) windowFeatures;



The remaining three agent methods are all related to the pop-up prompt box, for the Web interface three kinds of balloon (warning box, confirmation box, input box) correspond to three proxy methods respectively. The following is just an example of a warning box.


 code as follows:

/**
* Called when a pop-up warning box is available in the Web interface
*
* @param WebView Implement the webview of the agent
* @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 increasing the interaction between the app and the web side, and it can directly convert the received JS script to OC or Swift object. (Of course, the UIWebView can also interact with the web through the "curve salvation" approach, the famous Cordova framework is this mechanism)


 code as follows:

Called when a script is received from the Web interface
-(void) Usercontentcontroller: (Wkusercontentcontroller *) Usercontentcontroller didreceivescriptmessage: ( Wkscriptmessage *) message;





2. Modify Info.plist
Note that from the beginning of iOS9, all involved in network operations, should be included in the Info.plist:









3. Load Web page
to import WebKit in Viewcontroller first:


 code as follows:

Import WebKit



And then:


 code 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 a Web site
Let URL = Nsurl (string: "Http://www.jianshu.com/users/040395b7230c/latest_articles")
Create a request
Let request = Nsurlrequest (url:url!)
Load Request
Webview.loadrequest (Request)
Add Wkwebview
Self.view.addSubview (WebView)
}



Operation Effect as shown:












4. Get page title
to display the caption, first embed a navigationcontroller in the Viewcontroller. With the navigation bar, we need to adjust the y-axis position of the WebView, prevent the navigation bar from hiding the upper part of the page, and write it in Viewdidload ():


 code 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 add in the Viewdidload ()


 code as follows:

Self.webview.navigationDelegate = Self



Note that the page title to be completed after the completion of the Web page to get, otherwise empty, so we use the ' processing Web loading complete ' This method:


 code as follows:

Func WebView (Webview:wkwebview, didfinishnavigation navigation:wknavigation!) {
Self.navigationItem.title = Self.webview.title
}



Operation Effect as shown:












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


code 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 used the GoBack () and the GoForward () method to determine whether the page could move forward or backward before moving forward or backward:


 code as follows:

Func Toback () {
If Self.webview.canGoBack {
Self.webview.goBack ()
}
}


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




Finally, add the call to the Setnavbar () method in Viewdidload ():


 code as follows:

Setnavbar ()



Operation Effect as shown:












6. Modify the Web page configuration
now, a seemingly simple browser is done, but if we change the URL to:
Http://csol2.tiancity.com/homepage/article/Class_1166_Time_1.html
In Viewdidload (), modify:


code as follows:

Let URL = Nsurl (string: "http://csol2.tiancity.com/homepage/article/Class_1166_Time_1.html")



We will find that the text on the list above, including the text clicked on the top bar has not responded, where is the problem? This is because the system has blocked unsecured connections. How to solve it? We are going to use the Createwebviewwithconfiguration () method in Wkuidelegate to allow navigation, first we have to set our own proxy, in Viewdidload () add:


 code as follows:

Self.webview.UIDelegate = Self



Secondly:


 code as follows:

Func WebView (Webview:wkwebview, Createwebviewwithconfiguration configuration:wkwebviewconfiguration, Fornavigationaction navigationaction:wknavigationaction, windowfeatures:wkwindowfeatures)-> WKWebView? {
Allow navigation if the target view is not empty
if! (Navigationaction.targetframe?) MainFrame!= Nil) {
Self.webview.loadRequest (Navigationaction.request)
}
return Nil
}



Run a bit, found that click Jump!





7. Processing JS Prompt box
now amend the Web site to



http://evt.tiancity.com/csol2/1565/home/index.php
In Viewdidload (), modify:


 code as follows:

Let URL = Nsurl (string: "http://evt.tiancity.com/csol2/1565/home/index.php")



Pull down, click ' Get Now ', you should appear in the prompt box, but found nothing happened. To do this, we have to deal with the JS box event. Remember the way it was first mentioned, as follows:


 code 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 (title: "OK", Style: Uialertaction. Default, Handler: {(_)-> Void in
Completionhandler ()
}))
Self.presentviewcontroller (Alert, animated:true, Completion:nil)
}



Here to create a warning box to display, now run again to see?!












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


code 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 the monitoring progress to the Web page, also in Viewdidload ():


code as follows:

Self.webview.addObserver (Self, Forkeypath: "Estimatedprogress", Options:NSKeyValueObservingOptions.New, Context: Nil



Re-processing KVO:


 code as follows:



Override Func Observevalueforkeypath (keypath:string, Ofobject object:anyobject?, change: [String:anyobject]?, Contex t:unsafemutablepointer&lt;void&gt;) {


if KeyPath = = "Estimatedprogress" {


Self.progBar.alpha = 1.0


Progbar.setprogress (Float (webview.estimatedprogress), animated:true)


The maximum value for the progress bar is 1.0


if (self.webview.estimatedProgress &gt;= 1.0) {


Uiview.animatewithduration (0.3, delay:0.1, Options:UIViewAnimationOptions.CurveEaseInOut, animations: {()-&gt; Void In


Self.progBar.alpha = 0.0


}, Completion: {(Finished:bool)-&gt; 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 do not add animation to make the progress bar after the completion of the load disappear, you will find that the progress bar has not been to the far right midway is gone. So we're going to use an animation to achieve it. In addition, if the self.progBar.progress = 0 sentence, that is, the function of clearing zeros to other methods, such as the start of the navigation to clear zero, you will find that the progress bar animation problems, will come to the rotation. In a word, how to deal with the animation of the progress bar is very exquisite, I tried many times to find this method relatively stable some. So I suggest you can change the style of the progress bar, that is, do not rely on the value of the display, such as the circle can be turned and so on. Now there are a lot of third-party libraries can be used, you can go to the cocoapods to find.





Also, don't forget that for KVO mode, add must be remove, or it will crash. We can add the remove when the view disappears:


 code as follows:

Override func Viewwilldisappear (Animated:bool) {
Webview.removeobserver (Self, Forkeypath: "Estimatedprogress")
}



We can change some website to try!





9. Final Effect Chart






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



Postscript
since Wkwebview compared to UIWebView consumes less memory, then we have to actually compare, we let them load the same site, the result is as shown
(Left is UIWebView, right is Wkwebview):





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.