Use of IOS UIWebView (basic knowledge) _ios

Source: Internet
Author: User

Just contact with the development of iOS for more than 1 years, now for the hybrid mobile end of the development of more and more popular, because the development cost, speed is better than the traditional app development, hybrid development is the traditional model and the PC Web page connected combination mode. So mention of the app's hybrid model development, in the Android development of WebView as a hybrid model development of the bridge, of course, in iOS also has a UIWebView component as a hybrid model development bridge, then the following on the uiwebview of some basic knowledge.

First, the basic use of UIWebView

1. Create UIWebView:

CGRect bouds = [[UIScreen manscreen]applicationframe];
uiwebview* WebView = [[UIWebView alloc]initwithframe:bounds];

2, set properties:

Webview.scalespagetofit = yes;//Automatically scales the page to fit the screen
Webview.detectsphonenumbers = yes;//automatically detects the phone number on the Web page, click to dial

3, display the page view UIWebView:

[Self.view Addsubview:webview];

4, loading content

nsurl* url = [Nsurl urlwithstring:@ "http://www.baidu.com"];//create 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 URL
nsurlrequest* request = [Nsurlrequest requestwithurl:url];// Create Nsurlrequest
[webview loadrequest:request];//load

UIWebView also supports loading a NSString object as a source. You can provide a base URL to guide how UIWebView objects follow links and load remote resources:

[WebView loadhtmlstring:myhtml baseurl:[nsurl urlwithstring:@ "http://baidu.com"]];

5, navigation

The UIWebView class manages the navigation of the browser, and you can control the forward and backward actions through the GoForward and GoBack methods:

[WebView GoBack];
[WebView GoForward];
[WebView reload];//overload
[webview stoploading];//Cancel loading content

6. Uiwebviewdelegate Principal Agent

UIWebView supports a set of delegate methods that will be notified at specific times. To use these methods, you must first set the WebView delegate:

Webview.delegate = self;

The first argument for each of the following delegate methods is a pointer to a uiwebview, so you can use a delegate for multiple page views.

-(BOOL) WebView: (uiwebview*) WebView shouldstartloadwithrequest: (nsurlrequest*) reuqest Navigationtype: ( Uiwebviewnavigationtype) navigationtype;//is notified when a Web page view is indicated to load content. Should return yes, which will load. You can get the reason for the request initiation by navigating the type parameter, which can be any of the following values:
uiwebviewnavigationtypelinkclicked
uiwebviewnavigationtypeformsubmitted
Uiwebviewnavigationtypebackforward
Uiwebviewnavigationtypereload
uiwebviewnavigationtypeformresubmitted
uiwebviewnavigationtypeother

UIWebView control loads a Web page's listener function method:



-(void) WebView: (uiwebview*) WebView Didfailloadwitherror: (nserror*) error;//is notified when an error occurs in the request load. Provides a Nsserror object to identify the type of error that occurred.

These are the basics of using UIWebView in iOS, followed by some UIWebView common points of attention.

Second, iOS UIWebView commonly used attention points:

1. Interacting with UIWebView, calling a function that requires a parameter in a Web page, requires a single quote, or double quotes (double quotes need to be escaped before the escape character plus \) and does not need to be preceded by a single or double quote when passing the JSON string:

-(void) Webviewdidfinishload: (UIWebView *) webview
{
nsstring *sendjsstr=[nsstring stringwithformat:@ " OpenFile (\ "%@\") ", jsdocpathstr];
[WebView stringbyevaluatingjavascriptfromstring:sendjsstr];
}

2, in this proxy method to determine the interaction with the WebView, through the HTML defined in the Protocol to achieve:

-(BOOL) WebView: (uiwebview*) WebView shouldstartloadwithrequest: (nsurlrequest*) Request Navigationtype: ( Uiwebviewnavigationtype) Navigationtype

3, only in the webview after loading the corresponding page in the ability to call the JS method. (the corresponding method is the 1th article).

4. Add background picture for WebView:

Approvalwebview.backgroundcolor=[uicolor Clearcolor];
approvalwebview.opaque=no;//This sentence is very important, webview is not transparent, no for transparent under WebView add a imageview display picture on it

5, Get WebView page content information:

NSString *docstr=[webview stringbyevaluatingjavascriptfromstring:@ "Document.documentElement.textContent"];// Get the Web page content information, here is a JSON string
Sbjsonparser *parserjson=[[[sbjsonparser Alloc]init]autorelease];
Nsdictionary *contentdic=[parserjson objectwithstring:docstr];//Converts a JSON string into a dictionary

6, the method of loading local files:

First method:
nsstring* path = [[NSBundle mainbundle] pathforresource:name oftype:@ "html" indirectory:@ "mobile"];// Mobile is the root directory, name is the file name, HTML is the file type
[WebView loadrequest:[nsurlrequest requestwithurl:[nsurl Fileurlwithpath:path] ]]; Load local file
//second method:
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 then open with WebView:

NSString *resourcedocpath = [[NSString alloc] Initwithstring:[[[[nsbundle Mainbundle] ResourcePath] Stringbydeletinglastpathcomponent] stringbyappendingpathcomponent:@ "Documents"];
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];
Deletes the file under the specified directory
nsfilemanager *magngerdoc=[nsfilemanager Defaultmanager];
[Magngerdoc Removeitematpath:filepath Error:nil];

8, processing webview display TXT document garbled problem:

if ([Thetype isequaltostring:@ ". txt"])
{
//txt Band-coded and without coding, with encoded, such as the UTF-8 format txt, without encoding, such as the ANSI format TXT
//not with, You can try GBK and GB18030 encodings in turn
nsstring* aStr = [[NSString alloc] Initwithdata:attachmentdata encoding:nsutf8stringencoding ];
if (!astr)
{
//encoded with GBK
astr=[[nsstring alloc] initwithdata:attachmentdata encoding:0x80000632];
if (!astr)
{
//GBK encoding is not available, and then GB18030 encoded
astr=[[nsstring alloc Initwithdata:attachmentdata] encoding:0 X80000631];
}
Typesetting through HTML language
nsstring* responsestr = [NSString stringWithFormat: @ "" "" "", "
%@" "/pre>" "" "
,
aStr];
[Attachmentwebview loadhtmlstring:responsestr baseurl:[nsurl fileurlwithpath:[[nsbundle MainBundle] BundlePath]];
return;
}

9. Use WebView to load local or network files throughout the process:

1. Loading a local PDF file into the Web view

-(void) viewdidload {
[super viewdidload];
nsstring *thepath = [[NSBundle mainbundle] pathforresource:@ "iphone_user_guide" oftype:@ "PDF" from the local load;
if (thepath) {
NSData *pdfdata = [NSData Datawithcontentsoffile:thepath];
[(UIWebView *) self.view loaddata:pdfdata mimetype:@ "application/pdf"
textencodingname:@ "Utf-8" BaseURL:nil];
}
//load
from Network [Self.mywebview loadrequest:[nsurlrequest requestwithurl:[nsurl urlwithstring:@ "http://www.apple.com/"]];
}

2. The Web-view delegate managing network loading

-(void) Webviewdidstartload: (UIWebView *) WebView
{//Starting the load, show the activity indicator in the status bar< C2/>[uiapplication sharedapplication].networkactivityindicatorvisible = YES;
-(void) Webviewdidfinishload: (UIWebView *) webview
{
//finished loading, hide the activity indicator in the Statu s bar
[uiapplication sharedapplication].networkactivityindicatorvisible = NO;
}
-(void) WebView: (UIWebView *) WebView didfailloadwitherror: (nserror *) error
{
//Load Error, hide the activity Indicator in the status bar
[uiapplication sharedapplication].networkactivityindicatorvisible = NO;
The error inside
the webview nsstring* errorstring = [NSString stringWithFormat:
@ "An error occurred:< c16/>%@ ",
error.localizeddescription];
[Self.mywebview loadhtmlstring:errorstring Baseurl:nil];
}

3. Stopping a load request when the Web view was to disappear

-(void) Viewwilldisappear: (BOOL) animated
{
if ([Self.mywebview loading]) {
[Self.mywebview stoploading] ;
}
Self.myWebView.delegate = nil; Disconnect the delegate as the WebView is hidden
[uiapplication sharedapplication]. networkactivityindicatorvisible = NO;
}
/************/
quoted from Apple's official document (displaying Web content)

10, find WebView in the ScrollView:

-(void) Addscrollviewlistener
{
uiscrollview* currentscrollview;
For (uiview* Subview in self.webView.subviews) {
if ([Subview Iskindofclass:[uiscrollview class]]) {
Currentscrollview = (uiscrollview*) subview;
Currentscrollview.delegate = self;}}

11, remove the shadow of WebView, made similar scrollview:

-(void) Clearbackgroundwithcolor: (uicolor*) color
{
//Remove WebView shadow
self.backgroundcolor = color;
For (uiview* subview in [self subviews])
{
if ([Subview Iskindofclass:[uiscrollview class]]) {for
(uiview* s Hadowview in [Subview subviews])
{
if ([Shadowview Iskindofclass:[uiimageview class]]) {
[Shadowview Sethidden:yes]}}}}

12, cancel the long press WebView on the link pop-up actionsheet problem:

-(void) Webviewdidfinishload: (UIWebView *) webview
{
[WebView stringbyevaluatingjavascriptfromstring:@] Document.documentElement.style.webkitTouchCallout = ' none '; '];
}

13, cancel the hyperlink loading problem on the WebView:

-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) Navigationtype
{
if (navigationtype==uiwebviewnavigationtypelinkclicked) {
return NO;
}
else {return
YES
}
}

14, WebView before ios5.1 bug: In the previous project using WebView loading attachments, WebView support doc,excel,ppt,pdf and other formats, but these attachments must first download to the local and then loaded into the WebView can be displayed, Exiting the attachment page causes the program to crash when the attachment is downloaded locally and just starts loading onto the webview. It crashes because the WebView control does not cancel the related agent internally, causing the program to crash after exiting.

WebView on 5.1 bugs: Before the project requirements to WebView can move around, but when loading the page to WebView caused the page load incomplete, the bug is due to the webview itself cache. (yet to be studied)

15, in the use of WebView Sina Weibo share, WebView will automatically save the login cookies caused the project to share the module some problems, delete the WebView cookie method:

-(void) Deletecookiefordominpathstr: (NSString *) thepath
{
//delete local Cookie,thepath for cookie path by printing cookie to know its path For
(Nshttpcookie *cookie in [[Nshttpcookiestorage sharedhttpcookiestorage] cookies]) {

if ([[Cookie Domain] Isequaltostring:thepath]) {

[[nshttpcookiestorage sharedhttpcookiestorage] deletecookie:cookie];}}

16. Use Flashscrollindicators in UIWebView

When using Uiscrollview, we can use the Flashscrollindicators method to display the scrolling identity and then disappear, telling the user that the page can be scrolled and that there will be more to follow. UIWebView is internally dependent on Uiscrollview, but there is no flashscrollindicators method, but this method can be used in other ways, as shown below.

For (id subview in [webview subviews])
{if ([Subview respondstoselector: @selector (flashscrollindicators)])
{
[subview flashscrollindicators];
}
}

The above code fragment can be used in the webviewdidfinishload callback, and Flash displays the scrolling identity after loading the Web page content.

17, according to the content to obtain UIWebView height:

Sometimes you need to adjust the height of the UIWebView according to different content, so that the UIWebView just loaded all the content, do not drag, the back will not leave white. There are two ways to get the appropriate height of the UIWebView based on the content of the load, but you need to use it in the Webviewdidfinishload callback when the content of the Web page finishes loading.

①. Use the Sizethatfits method.

-(void) Webviewdidfinishload: (UIWebView *) webview
{
CGRect frame = webview.frame;
Frame.size.height = 1;
Webview.frame = frame;
Cgsize fittingsize = [WebView Sizethatfits:cgsizezero];
Frame.size = fittingsize;
Webview.frame = frame;
}

The Sizethatfits method has a problem, if the current uiview size is larger than the right size, then return the current size, does not return the most appropriate size value, so before using Sizethatfits, the UIWebView height is set to the minimum, that is, 1, Then use the sizethatfits to return just the right size.

②, using JavaScript

-(void) Webviewdidfinishload: (UIWebView *) WebView
{CGRect frame = webview.frame;
NSString *fitheight = [WebView stringbyevaluatingjavascriptfromstring:@ "document.body.scrollHeight;"];
Frame.size.height = [Fitheight floatvalue];
Webview.frame = frame;
}

Summarize:

First of all, the basic use of the UIWebView control in the development of iOS for a preliminary explanation, mentioned the creation, setting properties, setting the background, how to load the content of the Web page a series of basic points, and then explain the use of UIWebView control often use the attention point, often need to use the place, need to , which makes the bridge---uiwebview control to develop the iOS app hybrid mode more understanding and familiar. UIWebView can not only load the URI provided by the server, but also can load local resource files, and can load the Web page interface code returned by the server, imagine UIWebView is how powerful a control bridge, later in the development of the use of more and more places.

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.