Skip to content

CheckThisCodeCarefully/Nuke

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

631 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

Features

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, store the image in the memory cache, and finally display it.

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

Reusing Targets

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

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

Supporting Custom Targets

A target can be any class that implements a Target protocol:

extension UIButton: Nuke.Target {
    func handle(response: Result<Image>, isFromMemoryCache: Bool) {
        setImage(response.value, for: .normal)
    }
}

Providing Custom Handlers

Nuke also has a flexible loadImage(with:into:handler:) method which lets you handle the response by passing a closure:

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 Request struct. A request can be created either with a URL or with a URLRequest.

var request = Request(url: url)
// var request = Request(urlRequest: URLRequest(url: url))

// A request has a number of options that you can change:
request.memoryCacheOptions.writeAllowed = false

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

Processing Images

Nuke provides an infrastructure for processing images and caching them. You can specify custom image processors using Processing protocol which consists of a single method process(image: Image) -> Image?:

struct GaussianBlur: Processing {
    var radius = 8

    func process(image: UIImage) -> UIImage? {
        return image.applyFilter(CIFilter(name: "CIGaussianBlur", withInputParameters: ["inputRadius" : self.radius]))
    }

    // `Processing` protocol requires `Equatable` to identify cached images.
    func ==(lhs: GaussianBlur, rhs: GaussianBlur) -> Bool {
        return lhs.radius == rhs.radius // If the processor has no parameters, simply return true
    }
}

// Usage:
let request = Request(url: url).processed(with: GaussianBlur())
Manager.shared.loadImage(with: request, into: imageView)

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 providing a target.

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

If you'd like to be able 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
  • Tracking Activities

And many more...

Using Memory Cache

You can get a directly 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 its 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.

See 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
Toucan (Deprecated) Toucan offers a simple API for processing images
FLAnimatedImage (Deprecated) Use FLAnimatedImage to load and display animated GIFs

Design

Nuke is designed to support dependency injection. It provides a set of protocols - each with a single responsibility - which manage loading, decoding, processing, and caching images. You can easily create and inject your own implementations of the following protocols:

Protocol Description
Loading Loads images
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 about 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 class which is used to store 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.0

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.0%
  • Other 1.0%