您的位置:首页 > 移动开发 > Swift

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

2016-06-14 15:00 323 查看

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

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

目录

快速学会Swift第三方库 Kingfisher篇
目录

编码之前
导入 Kingfisher

其他操作

基础操作

使用optionsInfo参数

回调函数

取消任务

下载器

缓存系统

预取

动态图片

深入学习

编码之前

导入 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, 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)


深入学习

这里列出了Kingfisher大多数操作,如果想要深入学习Kingfisher,可以前往GitHub-Kingfisher主页
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: