Swift 中的SDWebImage类似库Kingfisher
来源:互联网 发布:三菱gt1000编程软件 编辑:程序博客网 时间:2024/05/04 01:31
Kingfisher (中文名:翠鸟) 是一个异步下载和缓存图片的库,SDWebImage的Swift 实现版。
https://github.com/onevcat/Kingfisher
Requirements
- iOS 8.0+, tvOS 9.0+, watchOS 2.0+ or OS X 10.10+
- Xcode 7.3 or above
Installation
CocoaPods
source 'https://github.com/CocoaPods/Specs.git'platform :ios, '8.0'use_frameworks!pod 'Kingfisher', '~> 2.2'
Usage
Basic
最基本的使用方法:import KingfisherimageView.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中添加
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Options
Kingfisher默认会从cache或者disk中找原图,如果没有找到才去网络上下载,你也可以设置选项强制刷新,忽略已缓存的图片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.Callbacks
下载时(获取进度)或者下载完成(某些通知)需要做某些事情,这些可以写在回调中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!") })
Cancel Task
你可以取消下载任务,特别是在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()}
Downloader & Cache system
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()
Prefetching
还有一个预取功能:就是在展示图片前,提前获取一些图像和缓存,不必在真正使用的时候再去请求数据,这样有利于提高用户体验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的方法展示图片基本的使用大概就这些,如果想了解跟多,请去阅读相关文档。
1 0
- Swift 中的SDWebImage类似库Kingfisher
- Swift 中的SDWebImage类似库Kingfisher
- Swift 中的SDWebImage类似库Kingfisher
- Swift-Kingfisher图片下载库
- [快速学会Swift第三方库] Kingfisher篇
- swift_035(Swift之第三方库Kingfisher篇)
- Kingfisher(swift)介绍与使用
- Swift 集成Alamofire/Kingfisher/MJRefresh/MBProgressHUD的小项目
- swift 使用Kingfisher进行网络图片的下载
- Swift 中使用SDWebImage
- IOS(swift)-常见类库使用·SDWebImage使用
- Swift中类似C++和ruby中的final机制
- SDWebImage 在Swift中遇坑解决
- Swift类似宏定义
- swift 类似九宫格
- Swift之SDWebImage第三方框架
- Swift之SDWebImage第三方框架
- Swift使用SDWebImage:Ambiguous use of
- bat调用python命令
- map 和 hash_map 的使用方法
- 【追求进步】顺时针打印矩阵【继续理解】
- MySQL权限篇之DELETE及SELECT
- Java网络编程精解之ServerSocket用法详解
- Swift 中的SDWebImage类似库Kingfisher
- APP专项性能测试 TestNG ReportNG
- Unrecognized option: -XX:MaxPernSixe -386m
- android开发之应用Crash自动抓取Log_自动保存崩溃日志到本地
- leetcode 174. Dungeon Game
- tabcontrol 隐藏标签
- 为镶嵌数据集批量创建快视图
- vim中方向键无法正常使用解决
- 父子页面间的关系