我已經搜索了整個互聯網,找不到解決方案,因此決定向專家諮詢,這甚至有可能。是否有可能在webview上顯示之前預加載html
我有一個博客,我正在開發iOS應用程序,但它需要太多時間加載內容。
因此,有可能在用戶打開文章之前預載所有文章的html(而不是圖像),就像FB即時文章一樣。 FB即時文章被預先加載和緩存,當用戶打開它時,它會在閃存中打開,除非用戶打開它時下載的圖像。
目前我正在使用uiwebview,我正在用wkwebview替換它。
感謝您的幫助。
調用緩存
CachedArticles.shared.cacheArticles(self.articles) { success
print("cache creation finished, success: \(success)")
}
調用的WebView
tableView.deselectRow(at: indexPath, animated: true)
let webVC = storyboard!.instantiateViewController(withIdentifier:"NewsReaderViewController") as! NewsReaderViewController
webVC.article = self.articles?[indexPath.row]
navigationController?.pushViewController(webVC, animated: true)
緩存類
import UIKit
class CachedArticles: NSObject {
static let shared: CachedArticles = CachedArticles()
let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
func cacheArticles(_ articles: [ArticalClass]?, completion: @escaping (Bool)->()) {
guard let articles = articles else { return }
DispatchQueue.global().async {
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
var success = true
for article in articles {
guard let path = article.url, let url = URL(string: path), self.webArchive(forHeadline: article.headline!.replacingOccurrences(of: " ", with: "")) == nil else { continue }
print("caching article: \(article)")
do {
let data = try Data(contentsOf: url)
let url = self.cacheFileURL(forHeadline: article.headline!)
STWebArchiver().archiveHTMLData(data, textEncoding: "UTF-8", baseURL: url, completionBlock: { data in
(data! as NSData).write(toFile: url.path, atomically: true)
})
} catch let error {
success = false
print("Error: \(error)")
}
}
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
completion(success)
}
}
}
func webArchive(forHeadline: String?) -> URL? {
let url = cacheFileURL(forHeadline: forHeadline!)
return FileManager.default.fileExists(atPath: url.path) ? url : nil
}
private func cacheFileURL(forHeadline: String) -> URL {
let url = URL(fileURLWithPath: self.cachePath).appendingPathComponent(forHeadline.replacingOccurrences(of: " ", with: "")+".webarchive")
return url
}
}
我厭倦了,但它也提取/下載圖像以及非常耗費數據。 –
你能顯示代碼嗎? –
感謝您的回覆。更新了代碼。 –