0

我有一个 iOS 应用程序,其中部分逻辑是用JavaScript. 我创建了一个WKWebView加载初始.js文件的位置,但是在执行时,它需要从本地资源中读取其他文件。问题是我错过了如何实现这一目标的概念。

我已经尝试将每个单独的文件一个接一个地加载Swift到其中,webView但是手动加载的文件太多了。
不过,也许有一个 http 服务器可以Swift访问项目文件。我找到了这样这样的解决方案。
一种方法看起来很棒,但即使我这样做了,我仍然无法从我的 Xcode 项目结构中访问文件和文件夹。我创建了一个基本的 http 服务器和一个 DAV 服务器,添加了GET处理程序等。

也许我在设置它时做错了,但最后当我创建一个 http 对象时server,我仍然可以从我webView的 athttp://192.168.0.11:8080所以确保它已正确初始化并正常工作。

4

1 回答 1

0

回答我的问题,以便将来对某人有所帮助。我最后使用了这个库。看起来缺少一些配置,因此服务器动态地为所有页面和文件提供服务。我的代码是:

guard let websitePath = Bundle.main.path(forResource: "myFolderNameInProjectStructure", ofType: nil) else { return }
let httpServer = GCDWebServer()
httpServer.addGETHandler(forBasePath: "/", directoryPath: websitePath, indexFilename: nil, cacheAge: 3600, allowRangeRequests: true)
httpServer.addHandler(forMethod: "GET", pathRegex: "/.*\\.html", request: GCDWebServerRequest.self) { (request) in
    return GCDWebServerDataResponse(htmlTemplate: websitePath + request.path, variables: ["variable": "value"])
}
httpServer.start(withPort: 8080, bonjourName: "MC Local Server")

完成此配置并且服务器在您选择的端口上运行(我的是8080),您只需在应用程序中打开嵌入式浏览器(例如WKWebView)并加载

let url = URL(string: "http://localhost:8080/index.html")!
webView.load(URLRequest(url: url))

如果你只是想index.html在连接到/http 服务器时总是运行,你可以在httpServer.start()方法之前添加这个配置:

httpServer.addHandler(forMethod: "GET", path: "/", request: GCDWebServerRequest.self) { (request) in
    return GCDWebServerResponse(redirect: URL(string: "index.html")!, permanent: true)
}

现在webView只需连接到http://localhost:8080并加载您提供的文件即可GCDWebServerResponse

于 2020-12-18T09:24:23.727 回答