Kingfisher (中文名:翠鸟) 是一个异步下载和缓存图片的库,SDWebImage的Swift 实现版。
https://github.com/onevcat/Kingfisher
source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' use_frameworks! pod 'Kingfisher', '~> 2.2'
import Kingfisher imageView.kf_setImageWithURL(NSURL(string: "http://your_image_url.png")!)
imageView.kf_setImageWithURL(NSURL(string: "http://your_image_url.png")!, placeholderImage: nil)
let URL = NSURL(string: "http://your_image_url.png")! let resource = Resource(downloadURL: URL, cacheKey: "your_customized_key") imageView.kf_setImageWithResource(resource)
原因:苹果将原http协议改成了https协议,使用 TLS1.2 SSL加密请求数据。
解决办法:
在info.plist中添加
imageView.kf_setImageWithURL(NSURL(string: "your_image_url")!, placeholderImage: nil, optionsInfo: [.ForceRefresh])
let myCache = ImageCache(name: "my_cache") imageView.kf_setImageWithURL(NSURL(string: "your_image_url")!, placeholderImage: nil, optionsInfo: [.TargetCache(myCache)])这一般是你想使用某个指定缓存时使用
如果你需要在1s淡入图像视图(只适用于iOS平台):
imageView.kf_setImageWithURL(NSURL(string: "your_image_url")!,
placeholderImage: nil,
optionsInfo: [.Transition(ImageTransition.Fade(1))])
你也可以自由组合这些选项来定制行为:
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) let optionInfo: KingfisherOptionsInfo = [ .ForceRefresh, .DownloadPriority(0.5), .CallbackDispatchQueue(queue), .Transition(ImageTransition.Fade(1)) ]For more information about options, please see the
KingfisherOptionsInfo
in the documentation
.
imageView.kf_setImageWithURL(NSURL(string: "your_image_url")!, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in print("Download Progress: \(receivedSize)/\(totalSize)") }, completionHandler: { (image, error, cacheType, imageURL) -> () in print("Downloaded and set!") } )
你可以取消下载任务,特别是在table view 或者 collection view使用时很有用(在下载未完成滑动离开时取消任务)
imageView.kf_setImageWithURL(NSURL(string: "http://your_image_url.png")!) // The image retrieving will stop. imageView.kf_cancelDownloadTask()
如果你需要做更多事情,kf_setImageWithURL方法返回RetrieveImageTask
对象,你可以调用其cancel
方法取消下载任务
let task = imageView.kf_setImageWithURL(NSURL(string: "http://your_image_url.png")!) let urlShouldNotBeCancelled: URL = ... if task.downloadTask?.URL != urlShouldNotBeCancelled { task.cancel() }
Kingfisher采用默认的Downloader和Cache参数,可以通过KingfisherManager.sharedManager.downloader
和KingfisherManager.sharedManager.cache
对其参数进行设置。
let downloader = KingfisherManager.sharedManager.downloader // Download process will timeout after 5 seconds. Default is 15. downloader.downloadTimeout = 5 // requestModifier will be called before image download request made. downloader.requestModifier = { (request: NSMutableURLRequest) in // Do what you need to modify the download request. Maybe add your HTTP basic authentication for example. } // Hosts in trustedHosts will be ignore the received challenge. // You can add the host of your self-signed site to it to bypass the SSL. // (Do not do it unless you know what you are doing) downloader.trustedHosts = Set(["your_self_signed_host"])
let cache = KingfisherManager.sharedManager.cache // Set max disk cache to 50 mb. Default is no limit. cache.maxDiskCacheSize = 50 * 1024 * 1024 // Set max disk cache to duration to 3 days, Default is 1 week. cache.maxCachePeriodInSecond = 60 * 60 * 24 * 3 // Get the disk size taken by the cache. cache.calculateDiskCacheSizeWithCompletionHandler { (size) -> () in print("disk size in bytes: \(size)") }
// Clear memory cache right away. cache.clearMemoryCache() // Clear disk cache. This is an async operation. cache.clearDiskCache() // Clean expired or size exceeded disk cache. This is an async operation. cache.cleanExpiredDiskCache()
let urls = ["http://example.com/image1.jpg", "http://example.com/image2.jpg"].map { NSURL(string: $0)! } let prefetcher = ImagePrefetcher(urls: urls, optionsInfo: nil, progressBlock: nil, completionHandler: { (skippedResources, failedResources, completedResources) -> () in print("These resources are prefetched: \(completedResources)") }) prefetcher.start()你可以随时取消该功能
prefetcher.stop()
预取之后,你可以使用Kingfisher的方法展示图片
基本的使用大概就这些,如果想了解跟多,请去阅读相关文档。