Swift的图片下载、缓存、缩放库:Maple Bacon
Maple Bacon是一个用于iOS开发的图片下载、缓存、缩放Swift库。
使用MapleBacon
下载一张图片
The most straightforward way is theUIImageViewextension:
import MapleBacon … if let imageURL = NSURL(string: "…") { imageView.setImageWithURL(imageURL) }
or with an optional closure, if you want to check for a possible error:
if let imageURL = NSURL(string: "…") { imageView.setImageWithURL(imageURL) { (instance, error) in … } }
Using the ImageManager directly
You can also access the underlying handler directly for more advanced usage:
if let imageURL = NSURL(string: "…") { let manager = ImageManager.sharedManager manager.downloadImageAtURL(imageURL, completion: { (imageInstance, error) in … }) }
Scaling images
For the quality conscious among you, MapleBacon also allows for more advanced (and more expensive) scaling of downloaded images. Under the hood this uses Core Graphics. The simplest way to use this mode is to pass in acacheScaled: trueBool into theUIImageViewextension:
imageView.setImageWithURL(imageURL, cacheScaled: true) // Or the call back way imageView.setImageWithURL(imageURL, cacheScaled: true) { (imageInstance, error) in … }
This will cache the scaled version of the image in the background, so the whole computation is done only once. It respects both the size and contentMode of the imageView that you call this method on.
Alternatively, you can also access theResizerclass directly (and use it independently of downloading images).
Caching
MapleBacon will cache your images both in memory and on disk. Disk storage is automatically pruned after a week but you can control the maximum cache time yourself too:
let maxAgeOneDay: NSTimeInterval = 60 * 60 * 24 MapleBaconStorage.sharedStorage.maxAge = maxAgeOneDay
You can also wipe the storage completely:
MapleBaconStorage.sharedStorage.clearStorage()
Or, should the app come under memory pressure, clear the in memory images only:
override func didReceiveMemoryWarning() { MapleBaconStorage.sharedStorage.clearMemoryStorage() }
MapleBacon supports multiple cache regions:
let storage = DiskStorage(name: "…")
This requires a little more effort on your end. In this case you'll need to use theImageManagerdirectly as described above and inject your custom storage instance there:
let storage = DiskStorage(name: "…") if let imageURL = NSURL(string: "…") { ImageManager.sharedManager.downloadImageAtURL(imageURL, storage: storage) { (imageInstance: ImageInstance?, error: NSError?) in … } }
项目主页:http://www.open-open.com/lib/view/home/1426132781607