Git Product home page Git Product logo

nuke's Introduction

A powerful image loading and caching framework which allows for hassle-free image loading in your app - often in one line of code.

Features

Nuke pulls together stable, mature libraries from Swift ecosystem into simple, lightweight package that lets you focus on getting things done.

Quick Start

Upgrading from the previous version? Use a migration guide.

Usage

Loading Images

Nuke allows for hassle-free image loading into image views and other targets.

Nuke.loadImage(with: url, into: imageView)

Reusing Views

Nuke.loadImage(with:into:) method cancels previous outstanding request associated with the target. No need to implement prepareForReuse. The requests also get cancelled automatically when the target deallocates (Nuke holds a weak reference to a target).

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    Nuke.loadImage(with: url, into: cell.imageView)
}

Customizing Requests

Each image request is represented by Request struct. It can be created with either URL or URLRequest and then further customized.

// Create and customize URLRequest
var urlRequest = URLRequest(url: url)
urlRequest.cachePolicy = .reloadIgnoringLocalCacheData
urlRequest.timeoutInterval = 30

var request = Request(urlRequest: urlRequest)

// You can add arbitrary number of transformations to the request
request.process(with: GaussianBlur())

// Disable memory caching
request.memoryCacheOptions.writeAllowed = false

// Load an image
Nuke.loadImage(with: request, into: imageView)

Providing Custom Handlers

Nuke has a flexible loadImage(with request: Request, into target: AnyObject, handler: @escaping Handler) method in which target is a simple reuse token. The method itself doesn't do anything when the image is loaded - you have full control over how to display it, etc. Here's one simple way to use it:

indicator.startAnimating()
Nuke.loadImage(with: request, into: view) { [weak view] in
    view?.handle(response: $0, isFromMemoryCache: $1)
    indicator.stopAnimating()
}

Supporting Custom Targets

Another way to use Nuke with custom targets is to implement Target protocol:

extension UIButton: Nuke.Target {
    func handle(response: Result<Image>, isFromMemoryCache: Bool) {
        guard let image = response.value else { return }
        self.setImage(image, for: .normal)
    }
}

Loading Images w/o Targets

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

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

If you'd like to be able to cancel the requests use a CancellationTokenSource:

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

Processing Images

You can specify custom image processors using Processing protocol which consists of a single method process(image: Image) -> Image?. Here's an example of custom image filter that uses Core 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.
    // If your processor doesn't have any parameters simply return `true`.
    func ==(lhs: GaussianBlur, rhs: GaussianBlur) -> Bool {
        return lhs.radius == rhs.radius
    }
}

See Toucan plugin for some useful image transformations

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

Plugins

Allows you to replace networking layer with Alamofire. Combine the power of both frameworks!

Gifu plugin allows you to load and display animated GIFs.

Toucan plugin provides a simple API for processing images. It supports resizing, cropping, rounded rect masking and more.

FLAnimatedImage plugin allows you to load and display animated GIFs with smooth scrolling performance and low memory footprint.

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 those 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

Nuke has a basic built-in DataLoader class that implements DataLoading protocol. It uses Foundation.URLSession which is a part of the Foundation's URL Loading System. Another part of it is Foundation.URLCache which provides a composite in-memory and on-disk cache for data. By default it is initialized with a memory capacity of 0 MB (Nuke only stores decompressed images in memory) and a disk capacity of 150 MB.

See Image Caching Guide to learn more about URLCache, HTTP caching, and more

If you'd like to use a third-party caching library check out Third Party Libraries: Using Other Caching Libraries

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

See Alamofire Plugin that implements DataLoading protocol using Alamofire framework

If you'd like to use your own network layer see Third Party Libraries: Using Other Networking Libraries

Memory Cache

Nuke provides a fast in-memory Cache that implements Caching protocol. It stores processed images ready to be displayed. Cache uses LRU (least-recently used) replacement algorithm. By default it is initialized with a memory capacity of 20% of the available RAM. As a good citizen Cache automatically evicts images on memory warnings, and removes most of the images when application enters background.

Requirements

  • iOS 9.0 / watchOS 2.0 / macOS 10.11 / tvOS 9.0
  • Xcode 8
  • Swift 3

License

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.