简体   繁体   English

WKWebView 加载 HTML 和 Javascript 但无法加载 CSS 文件

[英]WKWebView loads HTML and Javascript but fails to load CSS files

I have build a very simple WKWebView app using XCode 11 and Swift 5.我使用 XCode 11 和 Swift 5 构建了一个非常简单的 WKWebView 应用程序。

To do this I started with the default Hello World App and removed all the code from the two core AppDelegate methods and deleted the ContentView.swift file.为此,我从默认的 Hello World 应用程序开始,删除了两个核心 AppDelegate 方法中的所有代码,并删除了 ContentView.swift 文件。

I then added a new class file ViewController.swift with the following code然后我使用以下代码添加了一个新的类文件 ViewController.swift

import Cocoa
import WebKit

class ViewController: NSViewController, WKUIDelegate 
{

var webView: WKWebView!
override func loadView()
    {
    let webConfiguration = WKWebViewConfiguration ()
    webView = WKWebView (frame: CGRect(x:0, y:0, width:800, height:600), configuration:webConfiguration);
    webView.uiDelegate = self ;
    view = webView;
    }

override func viewDidLoad()
    {
    super.viewDidLoad()

    if let url = Bundle.main.url ( forResource: "TeamMap"
                                 , withExtension: "html"
                                 , subdirectory: "TM-MAC")
        {
        self.webView.loadFileURL ( url
                                 , allowingReadAccessTo: url);
        self.view = webView ;
        }
    }
}

I then added a View Controller to the storyboard and linked it to the above swift file and set it as the primary view controller.然后我将一个视图控制器添加到故事板并将其链接到上面的 swift 文件并将其设置为主视图控制器。

I then added a set of files to a new folder TM-MAC in the add folder structure with the following files然后我将一组文件添加到添加文件夹结构中的新文件夹 TM-MAC 中,其中包含以下文件

TeamMap.html
TeamMap.js
TeamMap.css
plus several other javascript and image files.

When this app is run a window appears within which the WKWebView can be seen and also inspected using Safari.当这个应用程序运行时,会出现一个窗口,在该窗口中可以看到 WKWebView,也可以使用 Safari 进行检查。

I find that the html and js file have both loaded but that the css file has not.我发现 html 和 js 文件都已加载,但 css 文件没有。 I am convinced there is no error in the css file as I have used the same three files in another XCode app written in Objective C.我确信 css 文件中没有错误,因为我在另一个用 Objective C 编写的 XCode 应用程序中使用了相同的三个文件。

I have found various similar reports inside StackOverflow and one thing I tried that still does not work is to change the variable passed into loadFileURL/allowingReadAccessTo from url to url.deletingLastPathComponent()我在 StackOverflow 中发现了各种类似的报告,我尝试过但仍然不起作用的一件事是将传递给 loadFileURL/allowingReadAccessTo 的变量从 url 更改为 url.deletingLastPathComponent()

对此的答案是添加以下代码行以在创建 Web 视图之前覆盖 func loadView()。

webConfiguration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs");

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

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