swift_035(Swift之第三方库Kingfisher篇)

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

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

(文档地址:http://cocoadocs.org/docsets/Kingfisher/1.6.1/Typealiases.html#/s:10Kingfisher32ImageDownloaderCompletionHandler

目录

其他操作

另外还需要在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, placeholderImage: nil, optionsInfo: [.TargetCache(myCache)])

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

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

回调函数

        imageView.kf_setImageWithURL(url, placeholderImage: nil, 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, optionsInfo: nil, 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)


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值