Basic knowledge of using of for IOS UIWebView

  • 2020-05-17 06:35:02
  • OfStack

I have just been involved in the development of IOS for more than 1 year. Now, the development of hybrid mobile terminal is becoming more and more popular, because the development cost and speed are better than the traditional APP development. Hybrid development is a mode combining the traditional mode with PC web terminal. As for the mixed mode development of APP, WebView is used as the bridge of mixed mode development in Android development, and UIWebView is also used as the bridge of mixed mode development in IOS, so the following is a detailed explanation of some basic knowledge of UIWebView.

1. 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 scale the page to fit the screen
webView. detectsPhoneNumbers = YES; // automatically detect the phone number on the web page, click to dial

3. Display web page view UIWebView:

[self.view addSubview:webView];

4. Load the content


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

You can also load 1 local resource:


NSURL* url = [NSURL fileURLWithPath:filePath];// create URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];// create NSURLRequest
[webView loadRequest:request];// loading 

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

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

5, navigation,

The UIWebView class manages the browser's navigation actions internally, and you can control the forward and backward actions using the goForward and goBack methods:


[webView goBack];
[webView goForward];
[webView reload];// overloading 
[webView stopLoading];// Unload content 

6. UIWebViewDelegate entrusted agency

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

webView.delegate = self;

The first argument to each of the delegate methods below is a pointer to an UIwebview, so you can use one delegate for multiple web views.


-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*) reuqest navigationType: (UIWebViewNavigationType)navigationType;// Web views are notified when instructed to load content. Should return YES , this will load. The reason for request initiation can be obtained through the navigation type parameter, which can be any of the following values: 
UIWebViewNavigationTypeLinkClicked
UIWebViewNavigationTypeFormSubmitted
UIWebViewNavigationTypeBackForward
UIWebViewNavigationTypeReload
UIWebViewNavigationTypeFormResubmitted
UIWebViewNavigationTypeOther

UIWebView control load the page of the listening function method:

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

The above are the basic use points of UIWebView in IOS, and the following are some common points of UIWebView.

2. Common notes for UIWebView in IOS:

1. Interact with UIWebView. When calling the function that needs to pass parameters in web page, the parameter should be in single quotation mark or double quotation mark (the double quotation mark should be escaped before the escape character). When passing json string, there is no need to add single quotation mark or double quotation mark:


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

2. Determine the interaction with webView in this proxy method, which can be realized through the protocol defined in html:


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

3. The js method in the corresponding page can be called only after webView has been loaded. (the corresponding method is article 1).

4. Add background image for webView:

approvalWebView.backgroundColor=[UIColor clearColor];
approvalWebView. opaque = NO; // this sentence is very important, whether webView is opaque or not, no is transparent. It is ok to add an imageView display picture under webView

5. Get the content information of webView page:

NSString * docStr = [webView stringByEvaluatingJavaScriptFromString: @ "document. documentElement. textContent"]. // gets the web page content information, which is an json string
SBJsonParser *parserJson=[[[SBJsonParser alloc]init]autorelease];
NSDictionary * contentDic = [parserJson objectWithString: docStr]; // converts the json string into a dictionary

6. Method of loading local files:


// The first 1 Methods: 
NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:@"html" inDirectory:@"mobile"];//mobile It's the root directory, name Is the file name, html It's a file type 
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]]; // Load local files 
// The first 2 Methods: 
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 open it 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 files in the specified directory 
NSFileManager *magngerDoc=[NSFileManager defaultManager];
[magngerDoc removeItemAtPath:filePath error:nil];

8. Deal with the problem of scrambled txt documents displayed by webView:


if ([theType isEqualToString:@".txt"])
{
//txt There are two kinds of coding with and without coding, such as with coding UTF-8 format txt , without coding, such as ANSI format txt
// If you don't, you can try it one by one GBK and GB18030 coding 
NSString* aStr = [[NSString alloc] initWithData:attachmentData encoding:NSUTF8StringEncoding];
if (!aStr)
{
// with GBK coding 
aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000632];
}
if (!aStr)
{
// with GBK Code no , Then use GB18030 coding 
aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000631];
}
// through html Language typesetting 
NSString* responseStr = [NSString stringWithFormat:
@""
""
""
""
"%@"
"/pre>"
""
"",
aStr];
[attachmentWebView loadHTMLString:responseStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
return;
}

9. The entire process of loading local or network files using webView:

1, Loading a local PDF file into the web view


- (void)viewDidLoad {
[super viewDidLoad];
// Load from local 
NSString *thePath = [[NSBundle mainBundle] pathForResource:@"iPhone_User_Guide" ofType:@"pdf"];
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


NSURL* url = [NSURL fileURLWithPath:filePath];// create URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];// create NSURLRequest
[webView loadRequest:request];// loading 
0

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


NSURL* url = [NSURL fileURLWithPath:filePath];// create URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];// create NSURLRequest
[webView loadRequest:request];// loading 
1

10. Find scrollview in webView:


NSURL* url = [NSURL fileURLWithPath:filePath];// create URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];// create NSURLRequest
[webView loadRequest:request];// loading 
2

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


- (void)clearBackgroundWithColor:(UIColor*)color
{
//  To get rid of webview The shadow of 
self.backgroundColor = 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. Unpress the link on webView to bring up the problem of actionSheet:


NSURL* url = [NSURL fileURLWithPath:filePath];// create URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];// create NSURLRequest
[webView loadRequest:request];// loading 
4

13. Cancel the hyperlink loading problem on webView:


NSURL* url = [NSURL fileURLWithPath:filePath];// create URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];// create NSURLRequest
[webView loadRequest:request];// loading 
5

14, webView ios5. 1 before bug: use webView loading attachment in previous projects, support doc webView, excel, ppt, pdf format, but these attachments must first and then downloaded to a local load on webView can show that when the attachment has just started after downloaded to a local load onto the webView, exit the attachment page will cause the program collapse at this time. The crash occurs when the webView control fails to cancel the relevant agent internally, causing the program to crash upon exit.

webView (bug on 5.1) : the previous project required webView to be able to influence the activity, but the page was not fully loaded when loading the page onto webView. This bug was caused by the cache of webView itself. (to be studied)

15. When using webView for sina weibo sharing, webView will automatically save the logged cookie, resulting in some problems with the sharing module in the project. Delete webView's cookie method:


NSURL* url = [NSURL fileURLWithPath:filePath];// create URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];// create NSURLRequest
[webView loadRequest:request];// loading 
6

16. Use flashScrollIndicators in UIWebView

When using UIScrollView, we can use the flashScrollIndicators method to display the scroll id and then disappear, informing the user that the page is scrollable, with more to come. UIWebView internally relies on UIScrollView, but it does not have the flashScrollIndicators method, but it can be used in other ways, as shown below.


NSURL* url = [NSURL fileURLWithPath:filePath];// create URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];// create NSURLRequest
[webView loadRequest:request];// loading 
7

The code snippet above can be used in the webViewDidFinishLoad callback, where flash displays the scrolling id when the page content has been loaded.

17. Get the height of UIWebView according to the content:

Sometimes it is necessary to adjust the height of UIWebView according to different content, so that UIWebView just fits all the content without dragging and without leaving any blank behind. There are two ways to get the appropriate height of UIWebView based on the loaded content, but both are available after the page content has been loaded, that is, in the webViewDidFinishLoad callback.

. 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;
}

There is a problem with the sizeThatFits method. If the current size of UIView is larger than the right size, it will return the current size without returning the best size value. So before using sizeThatFits, set the height of UIWebView to the minimum of 1, and then sizeThatFits will return the right size.

Use JavaScript


NSURL* url = [NSURL fileURLWithPath:filePath];// create URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];// create NSURLRequest
[webView loadRequest:request];// loading 
9

Conclusion:

First the basic use of UIWebView controls in the development of IOS carries on the preliminary explanation, mentioned to create, set properties, set the background, how to load the web page content and so on a series of points, then use UIWebView controls often use attention, often need to use, need to pay attention to of place, to develop ios APP bridge of mixed mode - UIWebView more understanding, familiar with the control. UIWebView can not only load the URI provided by the server, but also load the local resource files, and can also load the web interface code returned by the server. It is conceivable that UIWebView is a powerful 1 control bridge, which will be used in more and more places in the future development.


Related articles: