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