在尚未显示的UIViewController上预加载UIWebView

Alb*_*haw 9 load objective-c uiwebview uiviewcontroller ios

我有一个应用程序,在最后一个UIViewController上有一个UIWebView ...用户浏览应用程序,最后他们可以转换(模态)到最终的UIViewController与UIWebView ...在它的viewDidLoad我有UIWebView加载页面.

问题是加载此页面大约需要8秒钟,这会让用户感到恼火.

如何提前加载UIWebView(就像首次启动应用程序时那样!)如果UIViewController还没有呈现呢?

Ser*_*uca 19

我在UIPageViewController中对UIWebView有同样的问题,我发现了一个更好的解决方案.

如果你是在FirstViewController和你的网页视图中的SecondViewController投放loadHTMLStringloadRequest方法在viewDidLoad您的SecondViewController,并呼吁[secondViewController.view layoutSubviews]在你的启动加载FirstViewController.

例如:

FirstViewController

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

SecondViewController

-(void)viewDidLoad{
    [super viewDidLoad];
    NSURL *url =[NSURL URLWithString:@"http://www.google.it"];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}
Run Code Online (Sandbox Code Playgroud)

  • 苹果建议@dwinnbrown,而不是调用layoutSubviews,最好调用:[_ secondcondController.view setNeedsLayout]; [_secondViewController.view layoutIfNeeded]; (8认同)
  • 真棒!我搜索了几个小时,没有找到解决方案.非常好的把戏!:) (2认同)

Eik*_*ike 5

你能做的是,加载html字符串

 NSString *htmlFile = [[NSBundle mainBundle] pathForResource:self.path ofType:@"htm"];
 NSError * error;
 NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:&error];
Run Code Online (Sandbox Code Playgroud)

当你显示webView时,在webView中加载这个内容

[self.webView loadHTMLString:htmlString baseURL:[[NSBundle mainBundle] bundleURL]];
Run Code Online (Sandbox Code Playgroud)

那么你的webview只需要渲染你的内容而不加载数据

///在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")
    }
Run Code Online (Sandbox Code Playgroud)

注意:它对WKWebView的工作方式相同