SoFunction
Updated on 2025-04-12

IOS's UIWebView usage (basic knowledge)

I have just been involved in IOS development for more than a year, and now it is becoming more and more popular for hybrid mobile development, because the development cost and speed are better than traditional APP development. Hybrid development is a model that combines traditional models with PC web pages. Then we mentioned the hybrid mode development of APP. In Android development, WebView is used as a bridge for hybrid mode development. Of course, there is also a UIWebView component in IOS to serve as a bridge for hybrid mode development. So let’s explain some basic knowledge of UIWebView in detail.

1. Basic use of UIWebView

1. Create a UIWebView:

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

2. Set properties:

= YES;//Automatically zoom the page to fit the screen
= YES;//Automatically detect the phone number on the web page, click to dial

3. Display the web view UIWebView:

[ addSubview:webView];

4. Load content

NSURL* url = [NSURL URLWithString:@""];//Create URLNSURLRequest* request = [NSURLRequest requestWithURL:url];//Create NSURLRequest[webView loadRequest:request];//load

You can also load a local resource:

NSURL* url = [NSURL fileURLWithPath:filePath];//Create URLNSURLRequest* request = [NSURLRequest requestWithURL:url];//Create NSURLRequest[webView loadRequest:request];//load

UIWebView also supports loading an NSString object as a source. You can provide it with a basic URL that guides how the UIWebView object follows the link and loads the remote resource:

[webView loadHTMLString:myHTML baseURL:[NSURL URLWithString:@""]];

5. Navigation

The UIWebView class will manage the browser's navigation actions internally. Through the goForward and goBack methods, you can control the forward and backward actions:

[webView goBack];
[webView goForward];
[webView reload];//Reload[webView stopLoading];//Cancel the content

6. UIWebViewDelegate proxy

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

= self;

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

-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*) reuqest navigationType: (UIWebViewNavigationType)navigationType;//Imported when the web page view is instructed to load content.  YES should be returned, which will load.  The reason for the request is initiated by the navigation type parameter, which can be any of the following values:UIWebViewNavigationTypeLinkClicked
UIWebViewNavigationTypeFormSubmitted
UIWebViewNavigationTypeBackForward
UIWebViewNavigationTypeReload
UIWebViewNavigationTypeFormResubmitted
UIWebViewNavigationTypeOther

The listening function method of UIWebView control loading web pages:

-(void)webViewDidStartLoad:(UIWebView*)webView;//Are notified when the web view has started loading a request.
-(void)webViewDidFinishLoad:(UIWebView*)webView;//After the web view ends loading a request, it is notified.
-(void)webView:(UIWebView*)webView DidFailLoadWithError:(NSError*)error;//Import to be notified when an error occurs in the request loading. An NSSError object is provided to identify the type of error that occurred.

The above is a detailed explanation of the basic usage points of UIWebView in IOS, and the following are some common points of note for UIWebView.

2. Common points of note for UIWebView in IOS:

1. Interact with UIWebView. When calling functions that need to be passed in the web page, the parameters need to be single quotes or double quotes (double quotes need to be escaped before the escape character). There is no need to add single quotes or double quotes when passing json strings:

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

2. In this proxy method, the interaction with the webView can be determined through the protocol defined in html:

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

3. Only after the webView is loaded, the js method in the corresponding page can be called. (The corresponding method is as follows: Article 1).

4. Add background image to webView:

=[UIColor clearColor];
=NO;//This sentence is very important. Is the webView opaque? No is transparent. Just add an imageView to display the image under the webView.

5. Obtain webView page content information:

NSString *docStr=[webView stringByEvaluatingJavaScriptFromString:@""];//Get the web page content information, here is a json string
SBJsonParser *parserJson=[[[SBJsonParser alloc]init]autorelease];
NSDictionary *contentDic=[parserJson objectWithString:docStr];//Convert json string to dictionary

6. Methods to load local files:

//The first method:NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:@"html" inDirectory:@"mobile"];//Mobile is the root directory, name is the file name, and html is the file type[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]]; //Load local file//The second method:NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
NSString *filePath = [resourcePath stringByAppendingPathComponent:@""];
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 it with webView:

NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];
 = [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 files in the specified directoryNSFileManager *magngerDoc=[NSFileManager defaultManager];
[magngerDoc removeItemAtPath:filePath error:nil];

8. Handle the problem of garbled code of webView display txt documents:

if ([theType isEqualToString:@".txt"])
{
//txt is divided into two types: encoding and without encoding. The ones with encoding are like UTF-8 format txt, and the ones without encoding are like ANSI format txt.//If you don't have it, you can try GBK and GB18030 encoding in turnNSString* aStr = [[NSString alloc] initWithData:attachmentData encoding:NSUTF8StringEncoding];
if (!aStr)
{
//Encoding with GBKaStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000632];
}
if (!aStr)
{
//It doesn't work if you encode it with GBK, then use GB18030 to encode it.aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000631];
}
//Type through html languageNSString* responseStr = [NSString stringWithFormat:
@""
""
""
""
"%@"
"/pre>"
""
"",
aStr];
[attachmentWebView loadHTMLString:responseStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
return;
}

9. Use webView to load local or network files as a whole process:

1、 Loading a local PDF file into the web view

- (void)viewDidLoad {
[super viewDidLoad];
//Load from localNSString *thePath = [[NSBundle mainBundle] pathForResource:@"iPhone_User_Guide" ofType:@"pdf"];
if (thePath) {
NSData *pdfData = [NSData dataWithContentsOfFile:thePath];
[(UIWebView *) loadData:pdfData MIMEType:@"application/pdf"
textEncodingName:@"utf-8" baseURL:nil];
}
//Load from the network[ loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"/"]]];
}

2、The web-view delegate managing network loading

- (void)webViewDidStartLoad:(UIWebView *)webView
{// starting the load, show the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// finished loading, hide the activity indicator in the status 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;
// report the error inside the webview
NSString* errorString = [NSString stringWithFormat:
@"An error occurred:
%@",
];
[ loadHTMLString:errorString baseURL:nil];
}

3、Stopping a load request when the web view is to disappear

- (void)viewWillDisappear:(BOOL)animated
{
if ( [ loading] ) {
[ stopLoading];
}
 = nil; // disconnect the delegate as the webview is hidden
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
/************/
Quote from Apple's official documentation(displaying web content)

10. Find scrollview in webView:

- (void) addScrollViewListener
{
UIScrollView* currentScrollView;
for (UIView* subView in ) {
if ([subView isKindOfClass:[UIScrollView class]]) {
currentScrollView = (UIScrollView*)subView;
 = self;
}
}
}

11. Remove the shadow of the webView and make it into a scrollView similar to:

- (void)clearBackgroundWithColor:(UIColor*)color
{
// Remove the shadow of the webview = color;
for (UIView* subView in [self subviews])
{
if ([subView isKindOfClass:[UIScrollView class]]) {
for (UIView* shadowView in [subView subviews])
{
if ([shadowView isKindOfClass:[UIImageView class]]) {
[shadowView setHidden:YES];
}
}
}
}
}

12. Unclicking the link on the webView to pop up the actionSheet:

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
[webView stringByEvaluatingJavaScriptFromString:@" = '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. Bugs of webView before ios5.1: In previous projects, webView uses webView to load attachments. webView supports doc, excel, ppt, pdf and other formats, but these attachments must be downloaded locally before being loaded on the webView before they can be displayed. When the attachments are just loaded on the webView after they are downloaded locally, quitting the attachment page at this time will cause the program to crash. The crash is because the webView control does not cancel the relevant proxy, which causes the program to crash after exit.

The bug in webView on 5.1: The previous project requires the webView to be able to move the activities, but when loading the page on the webView, the page is loaded incompletely. This bug is caused by the cache of the webView itself. (It remains to be studied)

15. When using webView to share on Sina Weibo, webView will automatically save logged-in cookies, resulting in some problems with the sharing module in the project. How to delete webView's cookies:

-(void)deleteCookieForDominPathStr:(NSString *)thePath
{
//Delete local cookies, thePath is the cookie path and can tell its path by printing cookiesfor(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 logo and then disappear, informing the user that this page can be scrolled, and there is more content later. UIWebView internally relies on UIScrollView, but it does not have the 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 snippet can be used in the webViewDidFinishLoad callback. After loading the web page content, flash displays the scrolling logo.

17. Obtain the height of the UIWebView based on the content:

Sometimes you need to adjust the height of the UIWebView according to different contents so that the UIWebView just installs all the content without dragging, and there will be no blank space behind it. There are two ways to get the appropriate height of the UIWebView based on the loading content, but both need to be loaded after the web page content is loaded, that is, it needs to be used in the webViewDidFinishLoad callback.

①.Use the sizeThatFits method.

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGRect frame = ;
 = 1;
 = frame;
CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
 = fittingSize;
 = frame;
}

There is a problem with the sizeThatFits method. If the size of the current UIView is larger than the right size, it returns the current size and will not return the most suitable size value. Therefore, before using sizeThatFits, set the height of the UIWebView to the smallest, that is, 1, and then use sizeThatFits to return the right size.

②. Use JavaScript

- (void)webViewDidFinishLoad:(UIWebView *)webView
{ CGRect frame = ;
NSString *fitHeight = [webview stringByEvaluatingJavaScriptFromString:@";"];
 = [fitHeight floatValue];
 = frame;
}

Summarize:

First, we provide a preliminary detailed explanation of the basic use of UIWebView controls in IOS development, and mention a series of basic points such as creating, setting properties, setting background, and how to load web content. Then we explain the common points of attention when using UIWebView controls, the areas that are often needed, and the areas that need to be paid attention to, so that we can better understand and familiarize ourselves with the bridge of developing the hybrid mode of ios APP. UIWebView can not only load the URI provided by the server, but also load the local resource files, and also load the web interface code returned by the server. It can be imagined how powerful UIWebView is, and more and more places will be used in development in the future.