简体   繁体   English

WKWebView不会加载本地html文件

[英]WKWebView does not load local html files

I have a WKWebView that works perfectly fine when given a URL or a URLRequest , but when I am trying to load local bundle html files into it, it just doesn't display anything. 当给定URLURLRequest ,我有一个WKWebView可以很好地工作,但是当我尝试将本地包html文件加载到其中时,它什么也不显示。

I am trying it like so: 我正在这样尝试:

let webView = WKWebView()

if let bundleURL = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "mySubDirectory/v1") {
    webView.loadFileURL(bundleURL, allowingReadAccessTo: bundleURL.deletingLastPathComponent())
}

I have tested that the bundleURL actually returns the right path and tried copying + pasting it in my browser at run time and it works great: file:///Users/myuser/Library/Developer/Xcode/DerivedData/FireApp-gugmufgdkejtfdhglixebzhokhfe/Build/Products/Debug-iphonesimulator/SteppingIntoFireFramwork.framework/mySubDirectory/v1/index.html 我已经测试过bundleURL实际上返回正确的路径,并在运行时尝试将其复制并粘贴到浏览器中,并且效果很好: file:///Users/myuser/Library/Developer/Xcode/DerivedData/FireApp-gugmufgdkejtfdhglixebzhokhfe/Build/Products/Debug-iphonesimulator/SteppingIntoFireFramwork.framework/mySubDirectory/v1/index.html

What could be the problem? 可能是什么问题呢?

If the URL works, then it seems that your webview is having trouble loading it. 如果该网址有效,则似乎您的Web视图无法加载它。

I once had this issue... Check that you don't have only “http” & “https” enabled for the allowed URL scheme 我曾经遇到过这个问题...检查您是否仅对允许的URL方案启用了“ http”和“ https”

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        let webView = WKWebView()
        let htmlPath = Bundle.main.path(forResource: "index", ofType: "html")
        let htmlUrl = URL(fileURLWithPath: htmlPath!, isDirectory: false)
        webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlUrl)
        webView.navigationDelegate = self
        view = webView
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Full solution here 完整解决方案在这里

Your web view is just a local temporary variable. 您的网络视图只是一个本地临时变量。 It has zero size and is not in the interface, so you never see anything happen. 它的大小为零,并且不在界面中,因此您永远不会看到任何事情。

Try to remove deletingLastPathComponent() from your example. 尝试从示例中删除deleteLastPathComponent()。 Also you can try to use load(request) instead of loadFileURL(). 您也可以尝试使用load(request)代替loadFileURL()。

if let bundleURL = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "mySubDirectory/v1") {
    let request = URLRequest(url: bundleURL)
    webView.load(request)
}    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM