Swift 中的SDWebImage类似库Kingfisher

Kingfisher

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
从3月24起 Kingfisher开始支持Swift 2.2,如果你需要支持Swift 2.1,那么需要Kingfisher的对应版本2.1.0

Installation

CocoaPods

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

pod 'Kingfisher', '~> 2.2'

Usage

Basic

最基本的使用方法:

import Kingfisher

imageView.kf_setImageWithURL(NSURL(string: "http://your_image_url.png")!)


下载时可以设置默认图片

imageView.kf_setImageWithURL(NSURL(string: "http://your_image_url.png")!, placeholderImage: nil)


在默认情况下,Kingfisher使用url当做cache的key。 你也可以自定义这个key 。

let URL = NSURL(string: "http://your_image_url.png")!
let resource = Resource(downloadURL: URL, cacheKey: "your_customized_key")

imageView.kf_setImageWithResource(resource)


在首次使用时,可能会有出现问题: Application Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. 

原因:苹果将原http协议改成了https协议,使用 TLS1.2 SSL加密请求数据。
解决办法:
在info.plist中添加
NSAppTransportSecurity


    NSAllowsArbitraryLoads
    

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.downloaderKingfisherManager.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)")
}


内存cache在收到memory warning时会自动清除,disk cache也会在条件满足时被清除,当然你也可以手动调用方法进行清除

// 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的方法展示图片


基本的使用大概就这些,如果想了解跟多,请去阅读相关文档。

你可能感兴趣的:(iOS,Kingfisher,SDWebImage,Swift图片缓存)