项目介绍:
项目简介
Mattress是一个将整个web页面储存到磁盘缓存中的Swift框架,不同于NSURLCache,但是两者可以共同作用。这对更快的预缓存Web组件,以及使Web组件可用于脱机浏览,都是十分有用的。
安装
Mattress包含一个CommonCrypto的封装,所以你可以在Swift中很方便的使用。你要保证Mattress和CommonCrypto框架都include到你的项目中。
Carthage(推荐)
首先需要安装Carthag e: Homebrew
$ brew update
$ brew install carthage
之后可将本项目添加到你的Carfile中
github “buzzfeed/Mattress” >= 1.0.0
然后你需要用Carthage建立,手动将Mattress和CommonCrypto框架集成到你的项目中。
$ carthage build
CocoaPods
首先使用RubyGems安装CocoaPods
$ gem install cocoapods
安装之后将该项目添加到Podfile
pod ‘Mattress’, ‘~> 1.0.0’
使用方法
首先要创建一个URLCache实例,在你的 application:didFinishLaunching: method 中将它设置为你的应用程序的共享缓存。
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let kB = 1024
let MB = 1024 * kB
let GB = 1024 * MB
let isOfflineHandler: (() -> Bool) = {
// This is for demonstration only.
// You should use Reachability or your preferred method to determine offline status
// and return a proper value here.
return false
}
let urlCache = Mattress.URLCache(memoryCapacity: 20 * MB, diskCapacity: 20 * MB, diskPath: nil,
mattressDiskCapacity: 1 * GB, mattressDiskPath: nil, mattressSearchPathDirectory: .DocumentDirectory,
isOfflineHandler: isOfflineHandler)
NSURLCache.setSharedURLCache(urlCache)
return true
}
为了在Mattress磁盘缓存中缓存一个网页,简单的调用URLCache的 diskCacheURL:loadedHandler: method。
NSLog(“Caching page”)
let urlToCache = NSURL(string: “https://www.google.com”)
if let
cache = NSURLCache.sharedURLCache() as? Mattress.URLCache,
urlToCache = urlToCache
{
cache.diskCacheURL(urlToCache, loadedHandler: { (webView) -> (Bool) in
/*
Note: The below code should work for fairly simple pages. However, if the page you are
attempting to cache contains progressively / lazily loaded images or other assets you
will also need to trigger any JavaScript functions here to mimic user actions and
ensure those assets are also loaded before returning true.
*/
let state = webView.stringByEvaluatingJavaScriptFromString("document.readyState")
if state == "complete" {
// Loading is done once we've returned true
return true
}
return false
}, completeHandler: { () -> Void in
NSLog("Finished caching")
}, failureHandler: { (error) -> Void in
NSLog("Error caching: %@", error)
})
}
缓存成功之后,你可以在一个UIWebView中简单的加载,它可以从Mattress缓存中加载,就像魔法一样。
github地址:https://github.com/buzzfeed/mattress