在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() }
}
RRR
1> Fred J...:
在这里阅读了一些关于文件URL的内容后,我能够解决问题.
这是代码
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet var containerView: UIView! = nil //allows the class to reference 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:////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
}
}
}
嗨,您能否准确描述您使用的路径而不是`file:/// /abc /`?谢谢