为什么我的XWebView使用文件方案提供index.html,如何更改它?

时间:2015-10-10 21:34:17

标签: ios swift wkwebview gcdwebserver

我使用WKWebView来提供单页网页应用的index.htmlember),如下所示:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let webview = WKWebView(
            frame: view.frame, 
            configuration: WKWebViewConfiguration()
        )
        view.addSubview(webview)

        let root = NSBundle.mainBundle().resourceURL!
        let url = root.URLByAppendingPathComponent("dist/index.html")
        webview.loadFileURL(url, allowingReadAccessToURL: root)

加载索引文件的效果很好。但索引文件是使用文件方案请求它的链接和资源?如果我在检查器中运行Safari时检查应用程序,我会看到所有本地资源的错误:

[Error] Failed to load resource: ... file:///dist/assets/css/vendor.css

index.html中的内容如下:

<link rel="stylesheet" href="./dist/assets/vendor.css">

我想要的是资源请求转到我设置的GCDWebServer

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    var webServer: GCDWebServer?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        self.webServer = GCDWebServer()
        self.webServer!.addGETHandlerForBasePath("/",
            directoryPath: NSBundle.mainBundle().bundlePath,            
            indexFilename: nil,
            cacheAge: 3600,
            allowRangeRequests: true
        )
        self.webServer!.startWithPort(8080, bonjourName: "GCD Web Server")
        print("GCD Server running at: \(self.webServer!.serverURL)")
        return true

我已将dist文件夹添加到Xcode中的包中。

我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

这就是HTML的工作原理。绝对的HREF与引用页面的来源无关。因此,如果images/foo.png上有file:///dir/index.html,则浏览器会请求file:///dir/images/foo.png

如果您需要浏览器从其他位置获取资源,则您需要在HTML中使用绝对网址(例如http://localhost:8080/whatever)。

答案 1 :(得分:0)

解决方案非常简单。我只需要使用index.html代替webview.loadRequest从localhost提供我的webview.loadFileURL

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let serverURL = appDelegate.webServer!.serverURL
let indexURL = serverURL.URLByAppendingPathComponent("dist/index.html")
webview.loadRequest(NSURLRequest(URL: indexURL))

正如Andrew Medico所指出的,href是相对于其父页面的,所以如果我从localhost提供index.html,那么我的所有资源也会从localhost请求。解决了。