Basic usage of UIWebView and UIWebView

Source: Internet
Author: User

Basic usage of UIWebView and UIWebView

I. basic use of UIWebView

1. Create a UIWebView:

CGRect bouds = [[UIScreen manScreen] applicationFrame];
UIWebView * webView = [[UIWebView alloc] initWithFrame: bounds];

2. Set attributes:

WebView. scalespageToFit = YES; // automatically scales the page to adapt to the screen
WebView. detectsPhoneNumbers = YES; // automatically checks the phone number on the webpage, and click

3. display the webpage view UIWebView:

[Self. view addSubview: webView];

4. Load content

NSURL * url = [NSURL URLWithString: @ "http://www.baidu.com"]; // create a URL
NSURLRequest * request = [NSURLRequest requestWithURL: url]; // create NSURLRequest
[WebView loadRequest: request]; // Load

You can also load a local resource:

NSURL * url = [NSURL fileURLWithPath: filePath]; // create a URL
NSURLRequest * request = [NSURLRequest requestWithURL: url]; // create NSURLRequest
[WebView loadRequest: request]; // Load

UIWebView also supports loading an NSString object as the source. You can provide a basic URL to guide the UIWebView object to follow the link and load remote resources:

[WebView loadHTMLString: myHTML baseURL: [NSURL URLWithString: @ "http://baidu.com"];

 

5. Navigation

The UIWebView class manages browser navigation actions. You can use the goForward and goBack methods to control the forward and backward actions:

[WebView goBack];
[WebView goForward];
[WebView reload]; // reload
[WebView stopLoading]; // cancel loading content

 

6. UIWebViewDelegate delegate proxy

UIWebView supports a set of delegate methods, which are notified at a specific time. To use these methods, you must first set the webView delegate:

WebView. delegate = self;

The first parameter of each delegate method below is a pointer to a UIwebview. Therefore, you can use a delegate to multiple webpage views.

-(BOOL) webView :( UIWebView *) webView shouldStartLoadWithRequest :( NSURLRequest *) reuqest navigationType: (UIWebViewNavigationType) navigationType; // when the webpage view is instructed to load the content, it is notified. YES should be returned for loading. You can obtain the reason for request initiation by using the navigation type parameter, which can be any of the following values:
UIWebViewNavigationTypeLinkClicked
UIWebViewNavigationTypeFormSubmitted
UIWebViewNavigationTypeBackForward
UIWebViewNavigationTypeReload
UIWebViewNavigationTypeFormResubmitted
UIWebViewNavigationTypeOther

Method of listening to the web page loaded by the UIWebView control:

-(Void) webViewDidStartLoad :( UIWebView *) webView; // you will be notified when the webpage view has started to load a request.
-(Void) webViewDidFinishLoad :( UIWebView *) webView; // you will be notified after the webpage view ends loading a request.
-(Void) webView :( UIWebView *) webView DidFailLoadWithError :( NSError *) error; // get a notification when an error occurs during request loading. An NSSError object is provided to identify the error type.

The above is a detailed explanation of the basic usage of UIWebView in IOS, followed by some common notes for UIWebView.

 

2. Notes for UIWebView in IOS:

1. interact with UIWebView. When calling a function on the web page that requires parameter passing, the parameter must contain single quotation marks or double quotation marks (double quotation marks must be escaped before escape characters plus \), when passing a json string, no single quotation marks or double quotation marks are required:

-(Void) webViewDidFinishLoad :( UIWebView *) webView
{
NSString * sendJsStr = [NSString stringWithFormat: @ "openFile (\" % @ \ ")", jsDocPathStr];
[WebView stringByEvaluatingJavaScriptFromString: sendJsStr];
}

2. Determine the interaction with webView in the proxy method, which can be achieved through the Protocol defined in html:

-(BOOL) webView :( UIWebView *) webView shouldStartLoadWithRequest :( NSURLRequest *) request navigationType :( UIWebViewNavigationType) navigationType

3. The js method on the corresponding page can be called only after webView is loaded. (For example, 1st corresponding methods ).

4. Add a background image for webView:

ApprovalWebView. backgroundColor = [UIColor clearColor];
ApprovalWebView. opaque = NO; // This sentence is very important. If webView is not transparent, no is transparent. You can add an imageView under webView to display the image.

5. Obtain the content of the webView page:

NSString * docStr = [webView stringByEvaluatingJavaScriptFromString: @ "document.doc umentElement. textContent"]; // obtain the content of the web page, which is a json string.
SBJsonParser * parserJson = [[[SBJsonParser alloc] init] autorelser];
NSDictionary * contentDic = [parserJson objectWithString: docStr]; // converts a json string to a dictionary.

6. How to load local files:

// Method 1:
NSString * path = [[NSBundle mainBundle] pathForResource: name ofType: @ "html" inDirectory: @ "mobile"]; // mobile is the root directory and name is the file name, html is a file type
[WebView loadRequest: [NSURLRequest requestWithURL: [NSURL fileURLWithPath: path]; // load local files
// Method 2:
NSString * resourcePath = [[NSBundle mainBundle] resourcePath];
NSString * filePath = [resourcePath stringByAppendingPathComponent: @ "mobile.html"];
NSString * htmlstring = [[NSString alloc] initWithContentsOfFile: filePath encoding: NSUTF8StringEncoding error: nil];
[Uiwebview loadHTMLString: htmlstring baseURL: [NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath];

7. download the file to this address and use webView to open it:

NSString * resourceDocPath = [[NSString alloc] initWithString: [[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent: @ "events"];
Self. filePath = [resourceDocPath stringByAppendingPathComponent: [NSString stringWithFormat: @ "maydoc % @", docType];
NSData * attachmentData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: theUrl];
[AttachmentData writeToFile: filePath atomically: YES];
NSURL * url = [NSURL fileURLWithPath: filePath];
NSURLRequest * requestObj = [NSURLRequest requestWithURL: url];
[AttachmentWebView loadRequest: requestObj];
// Delete the objects in the specified directory
NSFileManager * magngerDoc = [NSFileManager defaultManager];
[MagngerDoc removeItemAtPath: filePath error: nil];

8. Handle the Garbled text in the txt file displayed in webView:

If ([theType isstring tostring: @ ". txt"])
{
// Txt with encoding and without Encoding Two, with encoding such as UTF-8 format txt, without encoding such as ANSI format txt
// If not, you can try GBK and GB18030 encoding in sequence.
NSString * aStr = [[NSString alloc] initWithData: attachmentData encoding: NSUTF8StringEncoding];
If (! AStr)
{
// Use GBK for encoding
AStr = [[NSString alloc] initWithData: attachmentData encoding: 0x80000632];
}
If (! AStr)
{
// It cannot be encoded using GBK. It must be encoded using GB18030.
AStr = [[NSString alloc] initWithData: attachmentData encoding: 0x80000631];
}

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.