The use of Wkwebview for iOS development and the problems encountered

Source: Internet
Author: User

introduction of Wkwebview

UIWebView since IOS2, Wkwebview from IOS8 only, no doubt Wkwebview will gradually replace the heavy uiwebview. Simple tests show that UIWebView consumes too much memory and that peak memory is exaggerated. Wkwebview Web pages load faster, but not as much as memory. Some other advantages are listed below:

1, more support HTML5 features

2, the official claim up to 60fps rolling refresh rate and built-in gestures

3, Safari the same JavaScript engine, and allow JavaScript Nitro Library to load and use (UIWebView in the limit);

4, the uiwebviewdelegate and UIWebView split into 14 categories and 3 agreements (Official document description)

5, occupy less memory, in performance, stability, functional aspects have a great promotion (the most intuitive embodiment is to load the Web page is occupied by memory, simulator load Baidu and open source China site, Wkwebview occupy 23M, and UIWebView occupy 85M);

Additional use of more, increased load progress properties: Estimatedprogress

ii. Initialization of Wkwebview

1. First need to introduce the WebKit library

Import

2. The initialization method is divided into the following two kinds

1 2 3 4 Default initialization-(Instancetype) initWithFrame: (CGRect) frame; Initialize based on the configuration of the WebView-(instancetype) initWithFrame: (CGRect) frame configuration: (Wkwebviewconfiguration *) Configuration Ns_designated_initializer;

3. Load Web page and HTML code in the same way as UIWebView, the code is as follows:

1 2 3 Wkwebview *webview = [[Wkwebview alloc] initWithFrame:self.view.bounds];     [WebView loadrequest:[nsurlrequest requestwithurl:[nsurl urlwithstring:@ "http://www.baidu.com"]]; [Self.view Addsubview:webview];

Introduction of Attributes

1 2 3 4 5 6 7 8 9 10 11 12 13 14-15 16 Wkbackforwardlist: A list of previously visited Web pages that can be accessed by back and forward actions. Wkbackforwardlistitem:webview a page in a list of back columns. Wkframeinfo: Contains layout information for a Web page. Wknavigation: Contains the load progress information for a Web page. Wknavigationaction: Contains information that may allow navigation changes in the Web page to determine whether navigation changes are made. Wknavigationresponse: Contains the return content information that may change the navigation of the Web page to determine whether to make navigation changes. Wkpreferences: Outlines a webview preference setting. Wkprocesspool: Represents a Web content load pool. Wkusercontentcontroller: Provides a way to use JavaScript post information and inject script. Wkscriptmessage: Contains information sent from a Web page. Wkuserscript: Represents a user script that can be accepted by a Web page. Wkwebviewconfiguration: Initializes the WebView settings. Wkwindowfeatures: Specifies the window properties when the new page is loaded. Wknavigationdelegate: Provides a way to track the main window page loading process and to determine whether the main window and child windows are loading new pages. Wkscriptmessagehandler: Provides a callback method for receiving messages from a Web page. Wkuidelegate: Provides a method callback that displays a Web page with the native control.

Four, Wkwebview agent

Wkwebview has two delegate,wkuidelegate and wknavigationdelegate. Wknavigationdelegate mainly deal with a number of jumps, loading processing operations, wkuidelegate main processing JS script, confirmation box, warning boxes and so on. So wknavigationdelegate is more commonly used.

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16-17 #pragma mark-wknavigationdelegate//page start load call-(void) WebView: (Wkwebview *) WebView didstartprovisionalnavigation: ( Wknavigation *) navigation{}//Call when content starts returning-(void) WebView: (Wkwebview *) WebView didcommitnavigation: (wknavigation *)       navigation{}//page after the completion of the call-(void) WebView: (Wkwebview *) WebView didfinishnavigation: (wknavigation *) navigation{ ///Page load failure call-(void) WebView: (Wkwebview *) WebView didfailprovisionalnavigation: (Wknavigation *) navigation{}

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21-22   Call-  (void) WebView after receiving a server jump request: (wkwebview *) webview  Didreceiveserverredirectforprovisionalnavigation: (wknavigation *) navigation{      }//  determines whether to jump-  (void) WebView after receiving a response: (wkwebview *) webview  Decidepolicyfornavigationresponse: (wknavigationresponse *) Navigationresponse decisionhandler: (void   (^) (wknavigationresponsepolicy)) decisionhandler{           NSLog (@ "%@", navigationResponse.response.URL.absoluteString);     //Allow jump      decisionhandler (wknavigationresponsepolicyallow);     //Not allowed to jump     //decisionhandler (wknavigationresponsepolicycancel); //  before sending the request, decide whether to jump-  (void) WebView: (wkwebview *) Webview decidepolicyfornavigationaction: ( wknavigationaction *) Navigationaction decisionhandler: (void  (^) (wknavigationactionpolicy)) decisionhandler{&NBsp;          NSLog (@ "%@", navigationAction.request.URL.absoluteString);     //Allow jump      decisionhandler (wknavigationactionpolicyallow);     //Not allowed to jump     //decisionhandler (wknavigationactionpolicycancel); }

2. Wkuidelegate

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17-18 #pragma  mark - wkuidelegate//  to create a new WebView-  (wkwebview *) WebView: (WKWebView  *) Webview createwebviewwithconfiguration: (wkwebviewconfiguration *) configuration  Fornavigationaction: (wknavigationaction *) Navigationaction windowfeatures: (WKWindowFeatures *) windowfeatures{     return  [[wkwebview alloc]init];}//  input Box-  (void) WebView: (wkwebview *) Webview runjavascripttextinputpanelwithprompt: (nsstring *) prompt  DefaultText: (nullable nsstring *) Defaulttext initiatedbyframe: (wkframeinfo *) frame  Completionhandler: (void  (^) (nsstring * __nullable result)) completionhandler{      completionhandler (@ "http"); //  confirmation Box-  (void) WebView: (wkwebview *) Webview runjavascriptconfirmpanelwithmessage: (NSString  *) Message initiatedbyframe: (wkframeinfo *) Frame completionhandler: (void  (^) (bool result)) completionhandler{     Completionhandler (YES);}//  Warning Box-   (void) WebView: (wkwebview *) Webview runjavascriptalertpanelwithmessage: (nsstring *) message  initiatedbyframe: (wkframeinfo *) Frame completionhandler: (void  (^) (void)) CompletionHandler {     NSLog (@ "%@", message);      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)

1 2 Called when a script is received from the Web interface-(void) Usercontentcontroller: (Wkusercontentcontroller *) Usercontentcontroller Didreceivescriptmessage: (wkscriptmessage *) message;

4, Wkwebview loading JS

1 2 3 4 5 6 7 8 9 10   Picture scaling JS code nsstring *js = @ "var count = document.images.length;for " ( var i = 0; i < count; i++)  {var image =  document.images[i];image.style.width=320;}; Window.alert (' Find '  + count +  ' map '); ";   Initializes the Wkuserscript object according to the JS string wkuserscript *script = [[wkuserscript alloc]  initwithsource:js injectiontime:wkuserscriptinjectiontimeatdocumentend formainframeonly:yes];   Initializes wkwebviewconfiguration wkwebviewconfiguration *config = [[based on the generated Wkuserscript object wkwebviewconfiguration alloc] init]; [config.usercontentcontroller adduserscript:script]; _webview = [[wkwebview alloc] initwithframe:self.view.bounds configuration:config]; [_webview loadhtmlstring:@]! [] (http://upload-images.jianshu.io/upload_images/1204112-3c87ed90109ff19f.jpg?imageMogr2/auto-orient/strip% 7cimageview2/2/w/1240) " Baseurl:nil]; [self.view addsubview:_webview];

v. The pit in the process of Wkwebview use

1. Add custom view below Wkwebview

Because we have a need is to add a view below the page to show the relevant comments on the content of this link. When using UIWebView, the practice is very simple and brutal, add a custom view after UIWebView's ScrollView, and then change the ScrollView Contentsize property according to the view's height. Thought Wkwebview can also so simple and rough to engage, the result is not so.

First of all, change the contentsize attribute of Wkwebview's ScrollView, the system will change back to the original when the next frame rate is refreshed, so this road won't work. I immediately thought of another way to change the ScrollView Contentinset This system will not change back to the original, think Bob. Later, after two days, found that some of the pages of some areas of the Click event can not be answered, baffled, and finally think of the contentinset may be set to its impact, in fact it is so. Check to find out, and finally found a solution is that when the page load complete, under the page to spell a blank Div, the height is the height of the view you add, so that the page more than a blank area, the custom view is added to the blank area above. This is the perfect solution to this problem. Specific reference to the demo to write, the core code is as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16-17 Self.addview = [[UIView alloc] Initwithframe:cgrectmake (0, 0, ScreenWidth, addviewheight)]; Self.addView.backgroundColor = [Uicolor Redcolor];
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.