swift2 – 将本地css和js文件加载到WKWebView中

前端之家收集整理的这篇文章主要介绍了swift2 – 将本地css和js文件加载到WKWebView中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Swift 2.1.1& Xcode 7.1
我的代码使用WKWebView并将index.html加载为本地文件,但无法加载index.css和其他javascript文件,如head标记所示.

我最好的猜测是baseURL不正确,如果是这样,我该如何正确设置baseURL?谢谢

  1. import UIKit
  2. import WebKit
  3.  
  4. class ViewController: UIViewController {
  5. @IBOutlet var containerView: UIView! = nil //allows the class to refrence WKWebView
  6. var webView: WKWebView?
  7.  
  8. override func loadView() {
  9. super.loadView()
  10.  
  11. self.webView = WKWebView()
  12. self.view = self.webView!
  13. }
  14.  
  15. override func viewDidLoad() {
  16. super.viewDidLoad()
  17.  
  18. let HTMLDocumentPath = NSBundle.mainBundle().pathForResource("index",ofType: "html")
  19. let HTMLString: NSString?
  20.  
  21. do {
  22. HTMLString = try NSString(contentsOfFile: HTMLDocumentPath!,encoding: NSUTF8StringEncoding)
  23. let baseUrl = NSURL.fileURLWithPath("")
  24. webView!.loadHTMLString(HTMLString as! String,baseURL: baseUrl)
  25.  
  26. } catch {
  27. HTMLString = nil
  28. }
  29. }
  30.  
  31. override func didReceiveMemoryWarning() {
  32. super.didReceiveMemoryWarning()
  33. }

}

  1. <head>
  2. <Meta charset="UTF-8">
  3. <title>RRR</title>
  4. <link rel="stylesheet" href="jquery.mobile-1.4.5.css"/>
  5. <link rel="stylesheet" href="index.css"/>
  6. <script src="jquery-1.11.3.js"></script>
  7. <script src="jquery.mobile-1.4.5.js"></script>
  8. <Meta name="viewport" content="width=device-width"/>
  9. </head>

在阅读了有关文件URL的 here之后,我能够解决问题.

这是代码

  1. import UIKit
  2. import WebKit
  3.  
  4. class ViewController: UIViewController {
  5. @IBOutlet var containerView: UIView! = nil //allows the class to refrence WKWebView
  6. var webView: WKWebView?
  7.  
  8. override func loadView() {
  9. super.loadView()
  10.  
  11. self.webView = WKWebView()
  12. self.view = self.webView!
  13. }
  14.  
  15. override func viewDidLoad() {
  16. super.viewDidLoad()
  17.  
  18. let baseUrl = NSURL(string: "file:///<yourFilePath>/abc/")
  19. let path = NSBundle.mainBundle().pathForResource("abc/index",ofType: "html")
  20. let HTMLString: NSString?
  21.  
  22. do {
  23. HTMLString = try NSString(contentsOfFile: path!,encoding: NSUTF8StringEncoding)
  24. webView!.loadHTMLString(HTMLString as! String,baseURL: baseUrl )
  25.  
  26. } catch {
  27. HTMLString = nil
  28. }
  29. }
  30.  
  31. override func didReceiveMemoryWarning() {
  32. super.didReceiveMemoryWarning()
  33. }
  34. }

猜你在找的Swift相关文章