我有一个iOS应用程序,其部分逻辑写在JavaScript
中。我创建了一个WKWebView
我在哪里加载我的初始 .js
文件,但执行时,它需要从我的本地资源中的其他文件中读取。问题是我缺少如何实现这一目标的概念。
我尝试在 Swift
中逐个加载每个单独的文件。进入webView
但文件太多,无法手动加载。
我想,也许 Swift
有一个 http 服务器。它将有权访问项目文件。我找到了类似 this 的解决方案或this .
一种方法看起来很棒,但即使我这样做,我仍然无法从 Xcode 项目结构访问文件和文件夹。我创建了一个基本的http服务器和一个DAV服务器,添加了GET
处理程序等
也许我在设置时做错了什么,但最后当我创建 http server
的对象时,我仍然可以从我的 webView
访问它在http://192.168.0.11:8080
所以可以肯定它已正确初始化并正常工作。
最佳答案
回答我的问题,以便将来对某人有所帮助。我最后用了this图书馆。看起来缺少一些配置,因此服务器动态地提供所有页面和文件。我的代码是:
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))
如果你只是想在连接到http服务器的/
时总是运行index.html
,你可以在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
的文件就会加载。
关于ios - 使用 JavaScript 访问 WKWebView 中的本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65326798/