1

我正在使用 aWKWebView来提供index.html单页网络应用程序(ember),如下所示:

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 中的捆绑包中。

我在这里想念什么?

4

2 回答 2

1

这就是 HTML 的工作原理。非绝对的 HREF 相对于引用页面的来源。所以如果你有images/foo.pngon file:///dir/index.html,浏览器会请求file:///dir/images/foo.png

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

于 2015-10-11T15:07:04.597 回答
0

解决方案非常简单。我只需要index.html通过使用webview.loadRequest而不是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's 是相对于它们的父页面的,所以如果我index.html从 localhost 提供服务,那么我的所有资源也都是从 localhost 请求的。解决了。

于 2015-10-14T13:38:31.357 回答