Preloading webView doesn't work - trying to re

2019-05-31 03:55发布

问题:

I have a viewController with a webView where I am displaying a local html file.

The problem is that it takes some seconds before loading therefore I am trying to avoid this waiting time.

The best way I thought so far is the following: as soon as I get into the main page I will start to load the file into the webView, in this way when I will get into the infoViewController with the webView it will be already loaded.

Here is the code:

//mainViewController.m:

tempInfo = [[InfoViewController alloc]initWithNibName:@"InfoViewController" bundle:nil];

[tempInfo.webView123 loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"About" ofType:@"htm"]isDirectory:NO]]];
tempInfo.test =@"test";

As you can see I also added a test variable, when I get into the infoViewController the webView is not loaded but the test variable changed value. This means that it is passing the value for the test variable but it is not loading the html file into the webView.

Any idea?

回答1:

Im assuming you are using iOS.

A WebView is not cheap and the one that is supplied as part of SDK is less good than native Safari windows.

The reason that your variable is modified is that loadRequest is async.

You are effectively asking the Webview to startup & load your page from cold. The page completes load at a point in the future. You can find out when by implementing the appropriate delegate method.

Some things you might want to try.

If your view controller is single-shot ( use and discard ) try loading the request in initWithNibName and placing the webview in the hierarchy in viewDidLoad or viewWillAppear

Find out if its your page by loading a very simple "Hello World" text file. If the simple file takes a lot less time then maybe your page needs some optimization.

Use the page loading delegate methods

– webViewDidStartLoad:

– webViewDidFinishLoad:

– webView:didFailLoadWithError:

To work out if your assumptions with respect to the page "not loading" are correct.

Good luck.