简体   繁体   中英

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.

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.

I then added a new class file ViewController.swift with the following code

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.

I then added a set of files to a new folder TM-MAC in the add folder structure with the following files

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.

I find that the html and js file have both loaded but that the css file has not. 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.

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()

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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