预加载多个本地WebView

问题描述 投票:10回答:1

因为我可以找到一些过时的信息/不能解决我的问题,我决定再次提出这样的问题。 (看到过时/错误的解决方案:)


我的应用程序分为一个本机部分和一个HTML部分。 HTML将保存为本地文件(index.html),并应加载到myWebView视图中。

@IBOutlet weak var myWebView: UIWebView!
func loadWebview() {
    let url = Bundle.main.url(forResource: "index", withExtension: "html")
    let request = URLRequest(url: url!)
    myWebView.loadRequest(request)
    myWebView.scrollView.isScrollEnabled = false
    myWebView.allowsLinkPreview = false
    myWebView.delegate = self
}

因为我的DOM树非常大,所以从本机部分切换到Web部分(在按钮点击时)在第一次切换时需要很长时间 - 因为之后,我确信webView请求被缓存。

To my question:我怎样才能在app init上预加载WebView,以避免从本机切换到Web部分时出现白屏(可能持续0.5秒-1s)?

编辑:

WKWebView显示滚动条而UIWebView不显示!

使用(与UIWebView一样)这种样式:

::-webkit-scrollbar {
     display: none;
}

没有工作并添加这些行:

webview.scrollView.showsHorizontalScrollIndicator = false
webview.scrollView.showsVerticalScrollIndicator = false

也根本不工作。

ios swift user-interface web-applications webview
1个回答
6
投票

首先,你应该切换到WKWebViewUIVewViewno longer recommended供Apple使用。

其次,您可以创建一个Web视图池,这些视图会在应用程序启动时被创建并要求加载。这样,当用户切换到Web界面时,Web视图可能有机会完全加载。

为此你可以使用这样的类:

/// Keeps a cache of webviews and starts loading them the first time they are queried
class WebViewPreloader {
    var webviews = [URL: WKWebView]()


    /// Registers a web view for preloading. If an webview for that URL already
    /// exists, the web view reloads the request
    ///
    /// - Parameter url: the URL to preload
    func preload(url: URL) {
        webview(for: url).load(URLRequest(url: url))
    }

    /// Creates or returns an already cached webview for the given URL.
    /// If the webview doesn't exist, it gets created and asked to load the URL
    ///
    /// - Parameter url: the URL to prefecth
    /// - Returns: a new or existing web view
    func webview(for url: URL) -> WKWebView {
        if let cachedWebView = webviews[url] { return cachedWebView }

        let webview = WKWebView(frame: .zero)
        webview.load(URLRequest(url: url))
        webviews[url] = webview
        return webview
    }
}

并要求它在app启动期间有时预加载url:

// extension added for convenience, as we'll use the index url in at least
// two places
extension Bundle {
    var indexURL: URL { return self.url(forResource: "index", withExtension: "html")! }
}

webviewPreloader.preload(url: Bundle.main.indexURL)

第三,您可能需要在控制器中使用容器视图而不是实际的Web视图:

@IBOutlet weak var webviewContainer: UIView!

剩下的就是在需要时将预加载的Web视图添加到容器中:

func loadWebview() {
    // retrieve the preloaded web view, add it to the container
    let webview = webviewPreloader.webview(for: Bundle.main.indexURL)
    webview.frame = webviewContainer.bounds
    webview.translatesAutoresizingMaskIntoConstraints = true
    webview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    webviewContainer.addSubview(webview)
}

而不是最后,请注意保持Web视图的实例可能会带来性能损失 - 内存和CPU。

© www.soinside.com 2019 - 2024. All rights reserved.