如果您希望拥有更好的阅读体验,欢迎访问 我的开发笔记
为了加快页面的加载速度和在无网络时也能加载出来网页,所以项目把加载url的做法废弃了,把vue生成的dist文件,用webview本地加载,由于平时都是直接写url地址,所以第一次写的时候,翻了好多网上的文章,现在我只有一句话想说,大家别抄来抄去了,转发之前,自己先测试下吧。。。。。
-
读取本地的HTML
因为iOS的项目,最终编译运行后,所有的文件夹都会被忽略,导致资源文件都会在xxxx.app这个mainBundle中,然后网页的路径不对,网页就加载不出来,因此先创建一个web.bundle,把资源全放进去,加载的时候,用这个bundle加载,就解决了,路径错误的问题
func getUrl() -> URL? { if let bundlePath = Bundle.main.path(forResource: "web", ofType: "bundle"), let webBundle = Bundle(path: bundlePath) { return webBundle.url(forResource: "index.html#/game", withExtension: nil) } return nil }
-
HTML文件会需要根据URL中不同的Hash 来显示不同的页面。例如#/game显示游戏首页,所以对上边的代码稍作改造
func getUrlPath(hash path: String = "game") -> URL? { if let bundlePath = Bundle.main.path(forResource: "web", ofType: "bundle"), let webBundle = Bundle(path: bundlePath), let indexPath = webBundle.path(forResource: "index", ofType: "html") { let resource = indexPath + "#/" + path let url = URL(fileURLWithPath: resource) return url } return nil }
然后发现打开的页面是一片空白,最后用Safari调试,打开调试器tab,显示如图的错误,然后打印地址发现了问题,iOS自动的把url最后边的
#
转为了%23
了,导致vue的路由识别不了
知道了问题,然后在修改为如下代码,最终问题解决
func urlStringFrom(bundle named: String = "web", hash path: String = "game") -> String { if let bundlePath = Bundle.main.path(forResource: named, ofType: "bundle"), let webBundle = Bundle(path: bundlePath), let indexPath = webBundle.path(forResource: "index", ofType: "html") { let url = URL(fileURLWithPath: indexPath) return url.absoluteString + "#/" + path } return "http://192.168.1.48:8090" }