Nuke:一个强大的图像加载和缓存框架

网友投稿 842 2022-10-28

Nuke:一个强大的图像加载和缓存框架

Nuke:一个强大的图像加载和缓存框架

A powerful image loading and caching framework which allows for hassle-free image loading in your app.

Features

Load images into image views or other targetsTwo cache layers, fast LRU memory cacheAlamofire, FLAnimatedImage, Gifu extensionsFreedom to use networking, caching libraries of your choiceRxSwift extensions provided by RxNukeAutomated prefetching with Preheat librarySmall (~1000 lines), fast and reliable

Quick Start

Installation GuideDocumentationAPI Reference

Upgrading from the previous version? Use a migration guide.

If you have any questions or comments about Nuke feel free to hit me up on Twitter @a_grebenyuk.

Usage

Loading Images into Targets

You can load an image into an image view with a single line of code. Nuke will automatically load image data, decompress it in the background, cache the image, and display it.

Manager.shared.loadImage(with: url, into: imageView)

Reusing Targets

Nuke.loadImage(with:into:) method cancels previous outstanding request for a target. Nuke holds a weak reference to the target, when the target is deallocated the request is cancelled.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { ... cell.imageView.image = nil Manager.shared.loadImage(with: url, into: cell.imageView) ...}

Providing Custom Handlers

Nuke has a flexible loadImage(with:into:handler:) method which lets you handle the response any way you want. You can use it to implement custom transitions, show loading indicators, and more.

indicator.startAnimating()Manager.shared.loadImage(with: request, into: view) { [weak view] response, _ in view?.image = response.value indicator.stopAnimating()}

The target in this method is declared as AnyObject with which the requests get associated.

Customizing Requests

Each request is represented by a Request struct. A request can be created with either URL or URLRequest.

var request = Request(url: url)// var request = Request(urlRequest: URLRequest(url: url))// Change memory cache policy:request.memoryCacheOptions.writeAllowed = false// Track progress:request.progress = { completed, total in ...}Manager.shared.loadImage(with: request, into: imageView)

Processing Images

Nuke can process and cache loaded images for you. For example, to resize the image you can simply provide the desired size when creating a Request:

/// Target size is in pixels.let request = Request(url: url, targetSize: CGSize(width: 640, height: 320), contentMode: .aspectFill)

It's also easy to perform custom image transformations by providing a closure. For example, here's how you can use Toucan to create a circular avatar:

let request = Request(url: url).process(key: "circularAvatar") { Toucan(image: $0).maskWithEllipse().image}

Another way to process images is by implementing custom processors which conform to Processing protocol. Each processor should be Equatable which helps Nuke store processed images in a memory cache.

See Core Image Integration Guide for more info about using Core Image with Nuke

Loading Images w/o Targets

You can also use Manager to load images directly without a target.

Manager.shared.loadImage(with: url) { print("image \($0.value)")}

If you'd like to cancel the requests, use a cancellation token:

let cts = CancellationTokenSource()Manager.shared.loadImage(with: url, token: cts.token) { print("image \($0.value)")}cts.cancel()

Using RxNuke

RxNuke adds RxSwift extensions for Nuke and enables many common use cases:

Going from low to high resolutionLoading the first available imageShowing stale image while validating itLoad multiple images, display all at onceAuto retry on failures

And more...

Using Memory Cache

You can get a direct access to the default memory cache used by Nuke:

Cache.shared.costLimit = 1024 * 1024 * 100 // 100 MBCache.shared.countLimit = 100let request = Request(url: url)Cache.shared[request] = imagelet image = Cache.shared[request]

Preheating Images

Preheating (prefetching) means loading images ahead of time in anticipation of their use. Nuke provides a Preheater class that does just that:

let preheater = Preheater(manager: Manager.shared)// User enters the screen:let requests = [Request(url: url1), Request(url: url2), ...]preheater.startPreheating(for: requests)// User leaves the screen:preheater.stopPreheating(for: requests)

You can use Nuke in combination with Preheat library which automates preheating of content in UICollectionView and UITableView. With iOS 10.0 you might want to use new prefetching APIs provided by iOS.

Check out Performance Guide to see what else you can do to improve performance

Extensions

NameDescription
RxNukeRxSwift extensions for Nuke with examples of common use cases solved by Rx
AlamofireReplace networking layer with Alamofire and combine the power of both frameworks
GifuUse Gifu to load and display animated GIFs
FLAnimatedImageUse FLAnimatedImage to load and display animated GIFs

Design

Nuke is designed to support dependency injection. It provides a set of protocols, which can be used to customize image loading pipeline:

ProtocolDescription
LoadingLoads images
DataLoadingDownloads data
DataDecodingConverts data into image objects
ProcessingImage transformations
CachingStores images into memory cache

Data Loading and Caching

A built-in DataLoader class implements DataLoading protocol and uses Foundation.URLSession to load image data. The data is cached on disk using a Foundation.URLCache instance, which by default is initialized with a memory capacity of 0 MB (Nuke stores images in memory, not image data) and a disk capacity of 150 MB.

See Image Caching Guide to learn more about image caching

See Third Party Libraries guide to learn how to use a custom data loader or cache

Most developers either implement their own networking layer or use a third-party framework. Nuke supports both of those workflows. You can integrate your custom networking layer by implementing DataLoading protocol.

See Alamofire Plugin that implements DataLoading protocol using Alamofire framework

Memory Cache

Nuke provides a fast in-memory cache (Cache) which stores processed images ready to be displayed. Cache uses LRU (least recently used) replacement algorithm. It has a limit which prevents it from using more than ~20% of available RAM. As a good citizen, Cache automatically evicts images on memory warnings and removes most of the images when the application enters background.

Requirements

iOS 9.0 / watchOS 2.0 / macOS 10.11 / tvOS 9.0Xcode 9Swift 4

License

Nuke is available under the MIT license. See the LICENSE file for more info.

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:php 生成指定日期范围内的数组
下一篇:redis命令 info persistence
相关文章

 发表评论

暂时没有评论,来抢沙发吧~