IOS Study Notes 14-web (iii) WebView

Source: Internet
Author: User

IOS Study Notes 14-web (iii) WebView
1. WebView

WebView is an embedded browser control. There are two types of WebView in iOS:UIWebViewAndWKWebView, UIWebView is used after iOS2 and WKWebView is used in iOS8. There is no doubt that WKWebView will gradually replace the bulky UIWebView.

Advantages of WKWebView:
WKWebView supports more HTML5 features. WKWebView is faster, and the memory usage may be only 1/3 of the UIWebView ~ 1/4 WKWebView up to 60fps rolling refresh rate and rich built-in gestures WKWebView with the same JavaScript Engine as Safari WKWebView added loading progress attribute

Despite the advantages of WKWebView, there are still many projects that have not been upgraded to iOS8, and UIWebView is also necessary for learning. You can also compare WKWebView and UIWebView for better understanding.

Note: Xcode7 disables plain-coded HTTP requests (but not limited to HTTPS requests). Add the following fields to info. plist. Otherwise, the HTTP request cannot be responded.

Add App Transport Security SettingsAnd set Allow Arbitrary LoadsIs YES

Ii. UIWebView1. UIWebView loading request
-(Void) simpleUIWebViewTest {// 1. create a webview and set the size. "20" indicates the height of the status bar CGFloat width = self. view. frame. size. width; CGFloat height = self. view. frame. size. height-20; UIWebView * webView = [[UIWebView alloc] initWithFrame: CGRectMake (0, 20, width, height)]; // 2. create url nsurl * url = [NSURL URLWithString: @ "http://www.baidu.com"]; // 3. CREATE Request NSURLRequest * request = [NSURLRequest requestWithURL: url]; // 4. load the webpage [webView loadRequest: request]; // 5. finally, add the webView to the interface [self. view addSubview: webView]; self. webView = webView ;}
2. Practical loading functions of UIWebView
// Load the network request-(void) loadRequest :( NSURLRequest *) request;/* function: load the local HTML string as the local HTML string baseURL to determine the reference address of the htmlString, equivalent to HTML
The default address of all links on the page */-(void) loadHTMLString :( NSString *) string baseURL :( nullable NSURL *) baseURL; /* load binary data */-(void) loadData :( NSData *) data MIMEType :( NSString *) MIMEType characterEncodingName :( NSString *) characterEncodingName baseURL :( NSURL *) baseURL;The following is an example of loading an HTML string.
-(Void) loadLocalHTMLFileToUIWebView {// obtain the path of the local html file NSString * localHTMLPageName = @ "myPage"; NSString * path = [[NSBundle mainBundle] pathForResource: localHTMLPageName ofType: @ "html"]; // read the html string NSString * htmlString = [NSString stringWithContentsOfFile: path encoding: NSUTF8StringEncoding error: NULL] From the html file; // load the local HTML string [self. webView loadHTMLString: htmlString baseURL: [[NSBundle mainBundle] bundleURL];}

UIWebViewYou can load HTML pages and display pdf, word, txt, and various images. UseloadRequestThe URL loaded by the method is the URL path of pdf, word, txt, and various images. The corresponding file can be loaded, which is not demonstrated here.

3. webpage navigation method of UIWebView

When we browse the Web page, we often use navigation operations such as refreshing the web page, moving forward, and backward. There are also corresponding operations in UIWebView.

# Pragma mark-determines whether the property can be withdrawn @ property (nonatomic, readonly, getter = canGoBack) BOOL canGoBack; // whether it can forward @ property (nonatomic, readonly, getter = canGoForward) BOOL canGoForward; // whether the @ property (nonatomic, readonly, getter = isLoading) BOOL loading; # pragma mark-Operation Method // refresh the webpage-(void) reload; // stop loading the webpage-(void) stopLoading; // back-(void) goBack; // forward-(void) goForward;
4. There are four methods for the UIWebViewDelegate proxy method:
// Whether the webpage can be loaded or the url to be opened by js. by intercepting this url, you can interact with js-(BOOL) webView :( UIWebView *) webView shouldStartLoadWithRequest :( NSURLRequest *) request navigationType :( UIWebViewNavigationType) navigationType; // start to load the webpage-(void) webViewDidStartLoad :( UIWebView *) webView; // The webpage loading is complete-(void) webViewDidFinishLoad :( UIWebView *) webView; // webpage loading error-(void) webView :( UIWebView *) webView didFailLoadWithError :( NSError *) error;
5. Interaction between UIWebView and JavaScript

There are two main aspects: JS execution of OC code, OC to retrieve the written JS Code
* Run the OC code in JS:
JS cannot execute OC code, but it can be executed in disguise. JS can encapsulate the operations to be executed in the network request, and then OC intercepts this request and obtains the string parsing in the URL, here we use a method in the proxy protocol.

- (BOOL)webView:(UIWebView *)webView     shouldStartLoadWithRequest:(NSURLRequest *)request                 navigationType:(UIWebViewNavigationType)navigationType
OC:
A method using WebView stringByEvaluatingJavaScriptFromString
// Automatically locates JS Code. htmlLocationID is the location (given by JS developers) to automatically locate the code, you should call NSString * javascriptStr = [NSString stringWithFormat: @ "window. location. href = '# % @' ", htmlLocationID]; // webview Execution Code [self. webView stringByEvaluatingJavaScriptFromString: javascriptStr]; // obtain the titleNSString * title = [self. webView stringByEvaluatingJavaScriptFromString: @ "document. title "];
6. UIWebView integration code
-(Void) viewDidLoad {[super viewDidLoad]; [self initWebView];}-(void) initWebView {// 1. create a webview and set the size. "20" indicates the height of the status bar CGFloat width = self. view. frame. size. width; CGFloat height = self. view. frame. size. height-20; UIWebView * webView = [[UIWebView alloc] initWithFrame: CGRectMake (0, 20, width, height)]; // 2. create url nsurl * url = [NSURL URLWithString: @ "http://www.baidu.com"]; // 3. CREATE Request NSURLRequest * reque St = [NSURLRequest requestWithURL: url]; // 4. load the webpage [webView loadRequest: request]; // 5. finally, add the webView to the interface [self. view addSubview: webView]; self. webView = webView; webView. delegate = self;} # pragma mark sets the status of the forward and backward buttons-(void) setBarButtonStatus {if (_ webView. canGoBack) {_ barButtonBack. enabled = YES;} else {_ barButtonBack. enabled = NO;} if (_ webView. canGoForward) {_ barButtonForward. enabled = YES;} else {_ barBut TonForward. enabled = NO;}/* browser back */-(void) clickGoBackBtn {if (self. webView. canGoBack) {[self. webView goBack] ;}}/* browser forward */-(void) clickGoForwardBtn {if (self. webView. canGoForward) {[self. webView goForward] ;}}# pragma mark-UIWebViewDelegate proxy method # pragma mark starts to load // whether to allow webpage loading or obtain the url to be opened by js, intercept this url to interact with js-(BOOL) webView :( UIWebView *) webView shouldStartLoadWithRequest :( NSURLRequest *) request navigationTy Pe :( UIWebViewNavigationType) navigationType {// intercept URL. Interaction with JS is allowed here, but it is not written here, because it involves some JS knowledge and adds complexity NSString * urlString = [request. URL absoluteString]; urlString = [urlString encoding: NSUTF8StringEncoding]; NSArray * urlComps = [urlString componentsSeparatedByString: @ ": //"]; NSLog (@ "urlString =%@ --- urlComps =%@", urlString, urlComps); return YES ;}// start loading webpage-(void) webViewDidSt ArtLoad :( UIWebView *) webView {// display network request loading [UIApplication sharedApplication]. networkActivityIndicatorVisible = true;} // webpage Loading completed-(void) webViewDidFinishLoad :( UIWebView *) webView {// hide the network request loading icon [UIApplication sharedApplication]. networkActivityIndicatorVisible = false; [self setBarButtonStatus]; // obtain the html content NSLog (@ "% @", [self. webView stringByEvaluatingJavaScriptFromString: @ "document. title "]);} // webpage loading error-(voi D) webView :( UIWebView *) webView didFailLoadWithError :( NSError *) error {UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "system prompt" message: @ "network connection error! "Delegate: self cancelButtonTitle: nil otherButtonTitles: @" OK ", nil]; [alert show];}
Iii. WKWebView

At last, it was the turn of WKWebView to play the leading role in the future era. WKWebView needs to be imported

1. The usage of the WKWebView loading request is exactly the same as that of the UIWebView:
# Pragma mark-WKWebView simple use-(void) wkWebViewEasyUse {// 1. create WKWebView CGFloat width = self. view. frame. size. width; CGFloat height = self. view. frame. size. height-20; WKWebView * webView = [[WKWebView alloc] initWithFrame: CGRectMake (0, 20, width, height)]; // 2. create url nsurl * URL = [NSURL URLWithString: @ "http://www.baidu.com"]; // 3. CREATE Request NSURLRequest * request = [NSURLRequest requestWithURL: URL]; // 4. load Request [webView loadRequest: request]; // 5. add to view self. webView = webView; [self. view addSubview: webView];}

2. Practical Loading Method of WKWebView

Some UIWebView and WKWebView are available. WKWebView has an additional file loading method, and all the loading methods of WKWebView have return values.

/* Load request */-(WKNavigation *) loadRequest :( NSURLRequest *) request;/* load the local HTML string */-(WKNavigation *) loadHTMLString :( NSString *) string baseURL :( nullable NSURL *) baseURL;/* load local file */-(WKNavigation *) loadFileURL :( NSURL *) url allowingReadAccessToURL :( NSURL *) url; /* load binary data */-(WKNavigation *) loadData :( NSData *) data MIMEType :( NSString *) MIMEType characterEncodingName :( NSString *) characterEncodingName baseURL :( NSURL *) baseURL;
The display effect of the loadHTMLString method is different. For details, refer:

My HTML file mypage.html is as follows:
 
I am Kenshin Cui 

iOS Learn

It is estimated that the default font styles for loading HTML are different for the two webviews.

The following is an instance for loading local files:
/* Debug and load the mac local file */-(void) loadLocalFile {// 1. create a webview and set the size. "20" indicates the height of the status bar CGFloat width = self. view. frame. size. width; CGFloat height = self. view. frame. size. height-20; WKWebView * webView = [[WKWebView alloc] initWithFrame: CGRectMake (0, 20, width, height)]; // 2. create url userName: Computer userName NSURL * url = [NSURL fileURLWithPath: @ "/Users/userName/Desktop/bigIcon.png"]; // 3. load the file [webView loadFileURL: url allowingReadAccessToURL: url]; // Add the webView to the interface [self. view addSubview: webView];}

3. WKWebView webpage Navigation Method

It is not much different from UIWebView. It has more returned values, more attributes, and two more methods:
*reloadFromOrigin, Cache Loading
*goToBackForwardListItemTo jump to the specified history page.

The following is a list of webpage navigation methods:
@ Property (nonatomic, readonly) BOOL canGoBack; @ property (nonatomic, readonly) BOOL canGoForward; @ property (nonatomic, readonly, getter = isLoading) BOOL loading;-(WKNavigation *) goBack;-(WKNavigation *) goForward;-(WKNavigation *) reload;-(void) stopLoading;/* loading progress, value range: 0 ~ 1 */@ property (nonatomic, readonly) double estimatedProgress;/* whether to allow left and right gesture navigation. By default, */@ property (nonatomic) BOOL allowsBackForwardNavigationGestures is not allowed; /* Access History list */@ property (nonatomic, readonly, strong) WKBackForwardList * backForwardList;/* checks whether network data has changed. If no change exists, the cache is used, otherwise, the new request */-(WKNavigation *) reloadFromOrigin;/* is more powerful than forward and backward. You can jump to a specified history page */-(WKNavigation *) goToBackForwardListItem * :( WKBackForwardListItem;
4. WKWebView proxy

UIWebView has only one proxy, but WKWebView has several, but two are commonly used,
id navigationDelegate Andid< WKUIDelegate > UIDelegate:
*WKNavigationDelegate: The most common, andUIWebViewDelegateThe function is similar to that of tracking the loading process, including whether loading is allowed, loading started, Loading completed, and loading failed.
*WKUIDelegate: UI Interface related, native control support, three prompt boxes: input, confirmation, warning.

Listed below WKNavigationDelegateCommon proxy Methods
/* 1. before sending a request, decide whether to jump to */-(void) webView :( WKWebView *) webView handler :( WKNavigationAction *) navigationAction decisionHandler :( void (^) (WKNavigationActionPolicy) decisionHandler; /* 2. the page starts to load */-(void) webView :( WKWebView *) webView didStartProvisionalNavigation :( WKNavigation *) navigation;/* 3. after receiving the response header from the server, determine whether to redirect based on the response information. */-(Void) webView :( WKWebView *) webView handler :( WKNavigationResponse *) navigationResponse decisionHandler :( void (^) (WKNavigationResponsePolicy) decisionHandler;/* 4. when you get the webpage content, you need to inject Javascript. Here, add */-(void) webView :( WKWebView *) webView didCommitNavigation :( WKNavigation *) navigation;/* 5. after the page is loaded, call */-(void) webView :( WKWebView *) webView didFinishNavigation :( WKNavigation *) navigation;/* error-call when page loading fails */-(void) webView :( WKWebView *) webView didFailProvisionalNavigation :( WKNavigation *) navigation;/* Others-processing server redirection Redirect */-(void) webView :( WKWebView *) webView progress :( WKNavigation *) navigation;

Let's take a lookWKUIDelegateAlthough it is not necessary to implement several proxy methods, if the JSalert,confirm,promptMethod, we should implement the following proxy methods, and then call the iOS pop-up window here, becauseWKWebViewIn HTMLalert,confirm,promptThe method call will not pop up any more

Listed below WKUIDelegateCommon proxy methods:
/* In the input box, the method */-(void) webView :( WKWebView *) webView preview :( NSString *) prompt defatext text :( nullable NSString *) is called when the JS prompt method is called *) defaultText initiatedByFrame :( WKFrameInfo *) frame completionHandler :( void (^) (NSString * result) completionHandler;/* confirmation box, the confirm method of JS is called on the page. */-(void) webView :( WKWebView *) webView runJavaScriptConfirmPanelWithMessage :( NSString *) message initiatedByFrame :( WKFrameInfo *) frame completionHandler :( void (^) (BOOL result) completionHandler;/* warning box. If the alert method of JS is called on the page, this method is called */-(void) webView :( WKWebView *) webView runningcriptalertpanelwithmessage :( NSString *) message initiatedByFrame :( WKFrameInfo *) frame completionHandler :( void (^) (void) completionHandler;

WKWebView has more functions, such as interacting with JavaScript.

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.