CWebViewCache
需求
iOS 10.0+ | Xcode 9.0+ | Swift 4.0+
安装
CWebViewCache 通过 CocoaPods 提供。要安装它,只需将以下行添加到 Podfile 中
use_frameworks!
pod 'CSWebCache'
使用方法
您应该在应用程序的 application:didFinishLaunching:
方法中创建 URLCache 的一个实例,并将其设置为应用程序的共享缓存。
let kB = 1024
let MB = 1024 * kB
let GB = 1024 * MB
let isOfflineHandler: (() -> Bool) = {
/*
We are returning true here for demo purposes only.
You should use Reachability or another method for determining whether the user is
offline and return the appropriate value
*/
return true
}
let urlCache = CSWebCache.URLCache(memoryCapacity: 20 * MB, diskCapacity: 20 * MB, diskPath: nil,
CSDiskCapacity: 1 * GB, CSDiskPath: nil, CSSearchPathDirectory: .documentDirectory,
isOfflineHandler: isOfflineHandler)
CSWebCache.URLCache.shared = urlCache
要在 CSWebViewCache 的磁盘缓存中缓存网页,只需调用 URLCache 的 diskCacheURL:loadedHandler:
方法。
if let urlToCache = URL(string: "https://appchance.com/blog/how-to-create-your-own-pod") {
if let cache = URLCache.shared as? CSWebCache.URLCache {
cache.diskCacheURL(urlToCache, loadedHandler: { (webView) -> (Bool) in
let state = webView.stringByEvaluatingJavaScript(from: "document.readyState")
if state == "complete" {
// Loading is done once we've returned true
return true
}
return false
}, completeHandler: { () -> Void in
print("Finished caching")
}, failureHandler: { (error) -> Void in
print("Error caching: \(error)")
})
}
webview.loadRequest(URLRequest(url: urlToCache))
}
作者
Mayur Amipara
许可协议
CSWebCache 可在 MIT 许可协议下使用。有关更多信息,请参阅 LICENSE 文件。