A Swift/SwiftUI utility for caching and displaying images in SwiftUI Views

Related tags

Image FlowImage
Overview

FlowImage

A Swift/SwiftUI utility for caching and displaying images asynchronously. Built with Swift 5.5 and works with async/await.

Features:

  • Asynchronously loading images using async/await from Swift 5.5
  • Automatic caching of images. See FlowCache.
  • Automatic caching with automatic loading/error state management. See FlowImageView.

Install

To add FlowImage to your app, see: Doc: Adding Package Dependencies to Your App

Usage

Level 1: Use URLFlowImage to handle asynchronous loading of images.

We've provided a URLFlowImage that can be used to load images from an URL. Directly call getUIImage() on URLFlowImage instances can give you a simple async image loading. See example.

let image: UIImage? = nil
image = try? await yourURLFlowImage.getUIImage() // You can execute this in your view's .task{}

Level 2: Use FlowImage with FlowImageView to manage states.

It's annoying to handle the state of loading your image and display it correctly. Introducing FlowImageView. It has the following features:

  • Automatic caching: if you are using this image multiple times, prepareForDisplay() of that FlowImage will only be called once! If you are using URLFlowImage, it means that we will only download the image once.
  • Automatic state management: In the body of FlowImageView, we give you a value of type FlowImageViewState(link) so that you know what's going on.

Example (Link to sample App):

// Inside your view
FlowImageView(image: image) { uiimage, state in
    // First parameter (UIImage?): produced uiimage.
    // Second parameter: the current state of the image.
    ZStack {
        if state == .displaying {
            if let image = uiimage {
                // Being in here means we have a proper image to display
                Image(uiImage: image)
                    .resizable()
                    .aspectRatio(contentMode: .fit)

            } else {
                // If the image is nil and we are displaying, it means the
                // FlowImage that's passed in is nil.
                Text("No Image")
            }
        } else if state == .error {
            // If state == .error, it means an error occurred, and image
            // value is set to nil.
            Text("There was an error!")

        } else if state == .loading {
            if let image = uiimage {
                // If image is not nil when loading, it will be the image
                // before we started loading.
                Image(uiImage: image)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .colorMultiply(.init(red: 0.5, green: 0.5, blue: 0.5))

            }

            // We overlay a progress view if we are loading.
            ProgressView()
                .progressViewStyle(.circular)
        }
    }
}

Level 3: Implementing your own FlowImage

The image can be stored anywhere. In another project, the images are stored on Firestore. You can create your own FlowImage class that conforms to the protocol, and it will be seamlessly integrated with the result of the package. Here 's where FlowImage is defined. Refer to the later section named "Implementing FlowImage".

Level 4+: Just go read the code and learn what's going on.

  • Create an instance of FlowCache instead of using the shared one? Sure.
  • Create your own FlowImageView and interact with FlowImage directly while managing your own state? Sure.
  • Need a FlowImage instance that conforms to Equatable, Hashable, and/or Identifiable? Just use eraseToAnyFlowImage().

Implementing FlowImage

FlowImage is a protocol for you to implement. Once implemented, it will come with a lot of great utilities. A FlowImage should store all the necessary information to produce an image, and also defines how to produce it. It only requires 1 property and 3 methods:

protocol FlowImage {
    var id: ID { get }

    func prepareForDisplay() async throws -> FlowImage
    func getUIImage() async throws -> UIImage
    func hash(into hasher: inout Hasher)
}

var id: ID

FlowImage.ID is an alias for type String. You will need to provide an unique string so that other utilities (like FlowCache) can distinguish between different images.

prepareForDisplay()

This is where you do any preparation before displaying. After the preparation is done, return another FlowImage with prepared data. Usually you would want to return a DownloadedFlowImage which holds an UIImage reference. You may return a different FlowImage type if you want. As an example, during prepareForDisplay(), URLFlowImage will download the image from the URL, and store the downloaded image in a DownloadedFlowImage instance before returning it.

getUIImage()

This is where you produce the UIImage class for display. getUIImage() method should work without calling prepareForDisplay() first, so that it can work independent from a cache.

hash(into hasher: inout Hasher)

This is here so that we can hash any FlowImage type if needed. AnyFlowImage conforms to Hashable.

You might also like...
SDWebImageMockPlugin makes possible the creation of snapshot testing with views using SDWebImage to configure images
SDWebImageMockPlugin makes possible the creation of snapshot testing with views using SDWebImage to configure images

SDWebImageMockPlugin makes possible the creation of snapshot testing with views using SDWebImage to configure images.

SwiftUI view that download and display image from URL and displaying Activity Indicator while loading .

ViewWithActivityIndicator ViewWithActivityIndicator is a SwiftUI view that download and display image from URL and displaying Activity Indicator while

A SwiftUI view for displaying image histograms
A SwiftUI view for displaying image histograms

HistogramView A SwiftUI view for displaying image histograms. How do I use it? It's as simple as: HistogramView(image: myImage) Note: Both UIImage & N

Space! – an iOS widget displaying NASA's Astronomy Picture of the Day
Space! – an iOS widget displaying NASA's Astronomy Picture of the Day

Space! NASA's Astronomy Picture of the Day – now on your Home Screen with widgets! Space! displays the latest APOD photo curated by NASA every day. Se

IBrain - Displaying a Point Cloud Using Scene Depth
IBrain - Displaying a Point Cloud Using Scene Depth

Displaying a Point Cloud Using Scene Depth Present a visualization of the physic

LoremPicsum - Simple UIKit based app for displaying grid of pictures

LoremPicsum - Simple UIKit based app for displaying grid of pictures

Media view which subclasses UIImageView, and can display & load images, videos, GIFs, and audio and from the web, and has functionality to minimize from fullscreen, as well as show GIF previews for videos.
Media view which subclasses UIImageView, and can display & load images, videos, GIFs, and audio and from the web, and has functionality to minimize from fullscreen, as well as show GIF previews for videos.

I've built out the Swift version of this library! Screenshots Description ABMediaView can display images, videos, as well as now GIFs and Audio! It su

Simple CLI utility to save off an image from every webcam hooked into a mac

macOSCameraCapture Simple CLI utility to save off an image from every webcam connected to the macOS machine. This utility is meant for research and te

Autocrop - A face-aware crop utility using OSX's Vision framework

autocrop A high-performance face-aware crop utility using OSX's Vision framework

Releases(0.2.2)
  • 0.2.2(May 17, 2022)

  • 0.2.1(Mar 7, 2022)

  • 0.2.0(Mar 6, 2022)

    Significant Improvement from 0.1.0:

    • More Documentation.
    • FlowCache will now retry if the last request with the same id failed.
    • FlowCache is now a MainActor
    • FlowCache will let you subscribe to changes via combine publisher if someone forced recache and/or cleared the cache.
    • Some API Changes.
    • Bug fixes (what do you expect).
    Source code(tar.gz)
    Source code(zip)
  • 0.1.0(Feb 24, 2022)

Owner
王雪铮 Xuezheng Wang
UCSD Computer Science Major 22' UI / CG
王雪铮 Xuezheng Wang
Kingfisher is a powerful, pure-Swift library for downloading and caching images from the web

Kingfisher is a powerful, pure-Swift library for downloading and caching images from the web. It provides you a chance to use a pure-Swift way to work

Wei Wang 20.9k Dec 30, 2022
A high-performance image library for downloading, caching, and processing images in Swift.

Features Asynchronous image downloader with priority queuing Advanced memory and database caching using YapDatabase (SQLite) Guarantee of only one ima

Yap Studios 72 Sep 19, 2022
APNGKit is a high performance framework for loading and displaying APNG images in iOS and macOS.

APNGKit is a high performance framework for loading and displaying APNG images in iOS and macOS. It's built on top of a modified version of libpng wit

Wei Wang 2.1k Dec 30, 2022
ImageView - Component for loading and displaying different images aka SVG/PNG/JPG/JPEG

ImageView Component that loads and displays images(.svg/.png/.jpg/.jpeg) form as

Sergei 1 Mar 23, 2022
A UIActivityViewController to share images while displaying them as a nice preview.

PSActivityImageViewController Overview This view controller allows you to share an image the same way as a normal UIActivityViewController would, with

Peter Salz 11 Oct 19, 2022
iOS library for quickly displaying images while scrolling

Fast Image Cache is an efficient, persistent, and—above all—fast way to store and retrieve images in your iOS application. Part of any good iOS applic

Path Mobile Inc Pte. Ltd. 8.2k Jan 9, 2023
An extremely high-performance, lightweight, and energy-efficient pure Swift async web image loader with memory and disk caching for iOS and  Watch.

KFSwiftImageLoader KFSwiftImageLoader is an extremely high-performance, lightweight, and energy-efficient pure Swift async web image loader with memor

Kiavash Faisali 343 Oct 29, 2022
🍁🥓 Lightweight and fast Swift library for image downloading, caching and transformations

MapleBacon Introduction MapleBacon is a lightweight and fast Swift library for downloading and caching images. Example The folder Example contains a s

Jan Gorman 335 Nov 1, 2022
Twitter Image Pipeline is a robust and performant image loading and caching framework for iOS clients

Twitter Image Pipeline (a.k.a. TIP) Background The Twitter Image Pipeline is a streamlined framework for fetching and storing images in an application

Twitter 1.8k Dec 17, 2022
Focus on avatar caching.

Navi Navi is designed for avatar caching, with style. The name of Navi from movie Avatar. Requirements Swift 3.1, iOS 8.0 Swift 2.3, use version 0.5.0

null 114 Jun 30, 2022