Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreLoad UIWebView on a not yet displayed UIViewController

I have an app where on the very last UIViewController there is a UIWebView... the user navigates through the app and at the very end they can transition (modal) to the final UIViewController with a UIWebView... in it's viewDidLoad I have the UIWebView load the page.

The problem is it takes about 8 seconds to load this page and that annoys users.

How can I load the UIWebView way ahead of time (like when the app is first launched!) if that UIViewController hasn't even been presented yet?

like image 254
Albert Renshaw Avatar asked Feb 04 '14 21:02

Albert Renshaw


2 Answers

I had your same problem for UIWebView inside a UIPageViewController and I found a better solution.

If you are in FirstViewController and you have your webView in your SecondViewController put the loadHTMLString or loadRequest method in the viewDidLoad of your SecondViewController and call [secondViewController.view layoutSubviews] for start loading in your FirstViewController.

Ex:

FirstViewController

-(void)viewDidLoad{
    [super viewDidLoad];
    // _secondViewController -> An instance of SecondVieController
    [_secondViewController.view layoutSubviews];
}

SecondViewController

-(void)viewDidLoad{
    [super viewDidLoad];
    NSURL *url =[NSURL URLWithString:@"http://www.google.it"];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}
like image 100
Serluca Avatar answered Nov 10 '22 21:11

Serluca


What u can do is, load the html string

 NSString *htmlFile = [[NSBundle mainBundle] pathForResource:self.path ofType:@"htm"];
 NSError * error;
 NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:&error];

and when u display the webView load this content in your webView

[self.webView loadHTMLString:htmlString baseURL:[[NSBundle mainBundle] bundleURL]];

then your webview need only render your content and doesn't load the data

/// In Swift 2.0

    do{
        let path = NSBundle.mainBundle().pathForResource("theName", ofType: "html")!
        let html = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
        webView.loadHTMLString(html, baseURL: nil)
    }catch{
        print("Error is happend")
    }

Note: It works the same way for WKWebView

like image 24
Eike Avatar answered Nov 10 '22 19:11

Eike