[快速学会Swift第三方库] Kingfisher篇

[快速学会Swift第三方库] Kingfisher篇

Kingfisher是一个轻量的下载和缓存网络图片库。下载和缓存是异步进行操作,已经下载好的图片会缓存在内存和本地,极大得提高app的体验。

目录

编码之前

导入 Kingfisher

推荐使用CocoaPods进行导入,CocoaPods是一个负责管理iOS项目中第三方开源库的工具,安装CocoaPods之后使用命令行就能轻松地对所有第三方开源库进行安装和更新,而不需要每次上GitHub去下载。
CocoaPods的安装过程传送门:iOS 9 导入类库全面详尽过程(Ruby安装->CocoaPods安装->导入类库)
手动安装:GitHub-Kingfisher主页

装好CocoaPods后,修改Podfile文件内容为如下:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios,'9.0'
use_frameworks!

target 'Web' do
pod 'Kingfisher','~> 2.4'
end
xcodeproj 'Desktop/Web/Web.xcodeproj'

target后面为工程名,最后一行为工程路径(这里的Web是我的工程名)

再执行命令:

$ pod install

其他操作

另外还需要在Target->工程名->Build Settings->Search Paths->User Header Search Paths处添加Kingfisher所在的目录:

最后在你需要用到Kingfisher的类中加上

import Kingfisher

基础操作

let url = NSURL(string: "http://www.51work6.com/service/download.PHP?email=scuxiatian@foxmail.com&FileName=test1.jpg")!;

        //打开该URL地址图片
        imageView.kf_setImageWithURL(url)

        //如果打开失败,打开placeholderImage参数的图片
        imageView.kf_setImageWithURL(url,placeholderImage: UIImage(named: "sps.png"))

        //打开资源中的图片,如果本地缓存中没有,将从URL地址下载,以关键字"MyImage"保存起来,以便下次使用
        let resource = Resource(downloadURL: url,cacheKey: "MyImage");
        imageView.kf_setImageWithResource(resource);

运行效果如下:

使用optionsInfo参数

//强制刷新,无论图片是否已在缓存中,到从URL地址重新下载
        imageView.kf_setimageWithURL(url,placeholderImage: nil,optionsInfo: [.ForceRefresh])

        //自定义关键字为"MyImage"的ImageCache
        let myCache = ImageCache(name: "MyImage");
        //将打开图片存入指定关键字的缓存中,而不是认缓存
        imageView.kf_setimageWithURL(url,optionsInfo: [.TargetCache(myCache)])

        //图片以淡入方式出现,动画持续1秒
        imageView.kf_setimageWithURL(url,optionsInfo: [.Transition(ImageTransition.Fade(1))])

        //optionsInfo参数可以同时接受多个条件
        imageView.kf_setimageWithURL(url,optionsInfo: [.ForceRefresh,.TargetCache(myCache),.Transition(ImageTransition.Fade(1))])

回调函数

imageView.kf_setimageWithURL(url,optionsInfo: nil,//进度回调函数
        progressBlock: { (receivedSize,totalSize) in
            print(receivedSize / totalSize)
        //完成回调函数
        { (image,error,cacheType,imageURL) in
            print("complete")
        }

取消任务

如果下载的图片不再使用可以停止任务,多用于tableView和collectionview中的cell,当图片还没下载完成时,用户就滑动界面导致cell消失的情况。

imageView.kf_setimageWithURL(url)
        //停止图片的取回
        imageView.kf_cancelDownloadTask();

也可以利用kf_setimageWithURL函数的返回值(类型为RetrieveImageTask)来进行更多的管理操作

let task = imageView.kf_setimageWithURL(url)
        //取消任务
        task.cancel();

下载器

自定义下载器参数

//获取下载器
        let downloader = KingfisherManager.sharedManager.downloader
        //设置超时时间,认为15妙
        downloader.downloadTimeout = 5
        //requestModifier中的内容会在下载之前开始执行
        downloader.requestModifier = {
            (request: NSMutableuRLRequest) in
            self.imageView.image = UIImage(named: "sps.png")
        }
        //设置信任host
        downloader.trustedHosts = Set(["httpbin.org"])

缓存系统

自定义缓存参数

//获取缓存
        let cache = KingfisherManager.sharedManager.cache
        //设置最大磁盘缓存为50Mb,认为无限制
        cache.maxdiskCacheSize = 50 * 1024 * 1024
        //设置最大缓存时间为1天,认为1周
        cache.maxCachePeriodInSecond = 60 * 60 * 24
        //计算缓存占用的磁盘大小
        cache.calculatediskCacheSizeWithCompletionHandler { (size) in
            print(size)
        }
        //清空存储器缓存
        cache.clearMemoryCache()
        //清空磁盘缓存
        cache.cleardiskCache()
        //清空失效和过大的缓存
        cache.cleanExpireddiskCache()

预取

将一些图片显示到屏幕上之前,先预取到缓存。主要用于当你可以预知接下来会用到图片资源时,避免多次请求。

let urlString1 = "http://www.51work6.com/service/download.PHP?email=scuxiatian@foxmail.com&FileName=test1.jpg"
        let urlString2 = "http://www.51work6.com/service/download.PHP?email=scuxiatian@foxmail.com&FileName=test2.jpg"

        let urls = [urlString1,urlString2].map{NSURL(string: $0 )!}
        let prefetcher = ImagePrefetcher(urls: urls,progressBlock: nil) { (skippedResources,FailedResources,completedResources) in
            print("These resources are prefetched:\(completedResources)")
        }
        //开始预取,预取成功的图片处理方式跟ImageCache中缓存的图片一样
        prefetcher.start()
        //停止预取
        prefetcher.stop()

动态图片

加载动态图片只需要加上一行代码,设置imageView为AnimatedImageView,不设置也能加载,但是在动态图片较大的时候推荐进行该设置。

imageView = AnimatedImageView()
        imageView.kf_setImageWithURL(url)

深入学习

这里列出了Kingfisher大多数操作,如果想要深入学习Kingfisher,可以前往GitHub-Kingfisher主页

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...