+
Skip to content

woookDev/Nuke

 
 

Repository files navigation

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

Features

Nuke 7 is in development. If you'd like to contribute or have some suggestions or feature requests please open an issue, a pull request or send me a message on Twitter.

Quick Start

Upgrading from the previous version? Use a migration guide.

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 automatically.

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'd like. 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
    ...
}

// Update the request priority:
request.priority = .high

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

Deduplicating Requests

By default Nuke combines the requests with the same loadKey into a single task. The task's priority is set to the highest priority of registered requests and gets updated when requests are added or removed to the task. The task only gets cancelled when all the registered requests are.

Deduplication can be disabled using Loader.Options.

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 resolution
  • Loading the first available image
  • Showing stale image while validating it
  • Load multiple images, display all at once
  • Auto 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 MB
Cache.shared.countLimit = 100

let request = Request(url: url)
Cache.shared[request] = image
let 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)

let requests = urls.map {
    var request = Request(url: $0)
    request.priority = .low
    return request
}

// User enters the screen:
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

Name Description
RxNuke RxSwift extensions for Nuke with examples of common use cases solved by Rx
Alamofire Replace networking layer with Alamofire and combine the power of both frameworks
Gifu Use Gifu to load and display animated GIFs
FLAnimatedImage Use 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:

Protocol Description
DataLoading Downloads data
DataDecoding Converts data into image objects
Processing Image transformations
Caching Stores 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.0
  • Xcode 9
  • Swift 4

License

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

About

A powerful image loading and caching framework

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Swift 99.3%
  • Other 0.7%
点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载