加载本地css&将js文件导入WKWebView

时间:2016-01-04 18:08:32

标签: swift2 wkwebview xcode7.1

在Swift 2.1.1& Xcode 7.1
我的代码使用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()
}

}



   <head>
      <meta charset="UTF-8">
      <title>RRR</title>
      <link rel="stylesheet" href="jquery.mobile-1.4.5.css"/>
      <link rel="stylesheet" href="index.css"/>
      <script src="jquery-1.11.3.js"></script>
      <script src="jquery.mobile-1.4.5.js"></script>
      <meta name="viewport" content="width=device-width"/>
   </head>
&#13;
&#13;
&#13;

enter image description here

1 个答案:

答案 0 :(得分:6)

在对文件网址进行了一些阅读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()
}
}