iOS 加载网页, 加载本地html, 并缓存处理

笔者性懒,腹中无墨
app嵌html屡见不鲜, 本文描述加载简单的html网页。
首先说明需求: 有网的状态直接从获取html网页并且缓存, 无网状态先从缓存读取html, 若不成功则加载本地html文件, 并且将本地html文件写入缓存, 以便下次读取.

iOS 加载网页, 加载本地html, 并缓存处理_第1张图片
缓存html.png

1.加载html网页, viewWillAppear或者viewDidLoad.
以下QAUrl均为html完整的url

func loadHtml() {
    guard let url: URL = URL(string: QAUrl) else {return}
    webView.loadRequest(URLRequest(url: url))
}

2.若成功, 就在成功的代理方法里, 将网页端html写入缓存

func writeToCache() {
    let queue = DispatchQueue(label: "writeToCache")
    queue.async {
        let htmlResponseStr = try? String(contentsOf: URL(string: self.QAUrl)!, encoding: .utf8)
        let fileManager = FileManager.default
        let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last
        try? fileManager.createDirectory(atPath: (cachesPath?.appending("/Caches"))!, withIntermediateDirectories: true, attributes: nil)
        guard let path = cachesPath?.appending("/Caches/feedback.html") else{return}
        print("缓存网页html路径: \(path)")

        do {
            try  htmlResponseStr?.write(toFile: path, atomically: true, encoding: .utf8) 
        } catch  {
            return
        }
    }
}

3.不成功,在失败的代理方法里, 加载磁盘缓存或者本地html,其中isNetConnected是指是否连接到互联网, 默认是true,加载失败后置为false.
fileprivate var isNetConnected: Bool = true // 是否连接到互联网

func loadCachesOrLocalHtml() {
    isNetConnected = false
    let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last
    guard let path = cachesPath?.appending("/Caches/feedback.html") else {return}
    do {
        let htmlString = try? String(contentsOfFile: path, encoding: .utf8)
        guard let localPath = htmlString else { 
            guard let path = Bundle.main.path(forResource: "qa", ofType: "html", inDirectory: nil) else {return}
            guard let htmlString = try? String(contentsOfFile: path, encoding: .utf8) else {return}
            // 本地
            webView.loadHTMLString(htmlString, baseURL: nil)
            writeLocalToCache()
            return
        }
        // 磁盘缓存
        webView.loadHTMLString(localPath, baseURL: nil)
    }
}

4.同样,此次成功后,在代理方法里,将本地html文件写入缓存

  func writeLocalToCache() {
    
    let queue = DispatchQueue(label: "writeLocalToCache")
    queue.async {
        guard let path = Bundle.main.path(forResource: "qa", ofType: "html", inDirectory: nil) else {return}
        guard let htmlString = try? String(contentsOfFile: path, encoding: .utf8) else {return}
        let fileManager = FileManager()
        let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last
        try? fileManager.createDirectory(atPath: (cachesPath?.appending("/Caches"))!, withIntermediateDirectories: true, attributes: nil)
        guard let localPath = cachesPath?.appending("/Caches/feedback.html") else{return}
        print("缓存本地html路径: \(localPath)")

        do {
            try  htmlString.write(toFile: localPath, atomically: true, encoding: .utf8)
            
        } catch  {
            return
        }
    }
}

5.代理方法的里很简洁

// MARK: - 网页或者本地html加载完成 都会调用
func webViewDidFinishLoad(_ webView: UIWebView) {
    if isNetConnected {
        writeToCache()
    }
}

func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
    loadCachesOrLocalHtml()
}

6.需要注意的是
(1)拼接缓存地址时, 如果html的URL类似于"http://10.0.4.2:82/app/qa.html",不能作为地址拼接,否则无法缓存.
(2)笔者将拼接地址统一写成"/Caches/feedback.html",若有新的缓存,则地址被覆盖,不会导致缓存多个相同文件,一般无需清理或者导致内存警告
(3)本文不涉及缓存图片, js交互等问题

7.补充:
开发过程中,笔者又遇到了一个问题,有网的情况下,网页也可能出现加载不成功.这个时候如果只是加载网页就会什么都没有.所以在viewWillAppear或者viewDidLoad里应该有个判断

DispatchQueue.global().async {
    WebService.request("/app/qa.html").validate().responseData { response in
        let finish = response.result.isSuccess
        DispatchQueue.main.async {
            if finish {
                self.loadHtml()
            } else {
                self.loadCachesOrLocalHtml()
            }
        }
    }
}

如果请求request返回的finish是true即成功,则加载html网页,不成功则加载缓存.

你可能感兴趣的:(iOS 加载网页, 加载本地html, 并缓存处理)