在
Swift 2.1.1& Xcode 7.1
我的代码使用WKWebView并将index.html加载为本地文件,但无法加载index.css和其他javascript文件,如head标记所示.
我的代码使用WKWebView并将index.html加载为本地文件,但无法加载index.css和其他javascript文件,如head标记所示.
我最好的猜测是baseURL不正确,如果是这样,我该如何正确设置baseURL?谢谢
- import UIKit
- import WebKit
- class ViewController: UIViewController {
- @IBOutlet var containerView: UIView! = nil //allows the class to refrence WKWebView
- var webView: WKWebView?
- override func loadView() {
- super.loadView()
- self.webView = WKWebView()
- self.view = self.webView!
- }
- override func viewDidLoad() {
- super.viewDidLoad()
- let HTMLDocumentPath = NSBundle.mainBundle().pathForResource("index",ofType: "html")
- let HTMLString: NSString?
- do {
- HTMLString = try NSString(contentsOfFile: HTMLDocumentPath!,encoding: NSUTF8StringEncoding)
- let baseUrl = NSURL.fileURLWithPath("")
- webView!.loadHTMLString(HTMLString as! String,baseURL: baseUrl)
- } catch {
- HTMLString = nil
- }
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- }
}
在阅读了有关文件URL的
here之后,我能够解决问题.
这是代码
- import UIKit
- import WebKit
- class ViewController: UIViewController {
- @IBOutlet var containerView: UIView! = nil //allows the class to refrence WKWebView
- var webView: WKWebView?
- override func loadView() {
- super.loadView()
- self.webView = WKWebView()
- self.view = self.webView!
- }
- override func viewDidLoad() {
- super.viewDidLoad()
- let baseUrl = NSURL(string: "file:///<yourFilePath>/abc/")
- let path = NSBundle.mainBundle().pathForResource("abc/index",ofType: "html")
- let HTMLString: NSString?
- do {
- HTMLString = try NSString(contentsOfFile: path!,encoding: NSUTF8StringEncoding)
- webView!.loadHTMLString(HTMLString as! String,baseURL: baseUrl )
- } catch {
- HTMLString = nil
- }
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- }
- }