• Stars
    star
    401
  • Rank 103,997 (Top 3 %)
  • Language
    Objective-C
  • License
    BSD 2-Clause "Sim...
  • Created almost 10 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A flexible image caching library for image rich iOS applications

SGImageCache

A lightweight iOS image and data cache with built in queue management.

CocoaPods Setup

pod 'SGImageCache'

Typical Usage

  1. Attempt to load the image immediately from the cache, if it exists
  2. If the image is not available in the cache, fetch the image asynchronously.
  3. (optional) It is recommended to also xfade in your image using a UIView transition animation for a pleasing effect.
// Swift
if let image = SGImageCache.image(forURL: url) {
    imageView.image = image   // image loaded immediately from cache
} else {
    SGImageCache.getImage(url: url) { [weak self] image in
        self?.imageView.image = image   // image loaded async
    }
}
// Objective-C
if ([SGImageCache haveImageForURL:url]) {
    self.imageView.image = [SGImageCache imageForURL:url];  // image loaded immediately from cache
} else {
    __weak UIViewController *me = self;
    [SGImageCache getImageForURL:url].then(^(UIImage *image) {
        me.imageView.image = image;  // image loaded async        
    });
}

Advanced Usage

Get an image urgently

// Objective-C
[SGImageCache getImageForURL:url].then(^(UIImage *image) {
    if (image) {
        self.imageView.image = image;
    }
});
// Swift
SGImageCache.getImage(url: url) { [weak self] image in
    guard let self = self else { return }
    self.imageView.image = image    
}

This will add the fetch request to fastQueue (a parellel queue). All image fetching (either from memory, disk, or remote) is performed off the main thread.

Queue a fetch for an image that you'll need later

// Objective-C
[SGImageCache slowGetImageForURL:url];
// Swift
SGImageCache.slowGetImage(url: url)

This will add the fetch request to slowQueue (a serial queue). All image fetching (either from memory, disk, or remote) is performed off the main thread.

Adding image fetch tasks to slowQueue is useful for prefetching images for off screen content. For example if you have data for 100 table rows, but only 3 are on screen at a time, you would request the images for on screen rows from fastQueue with getImageForURL: and add the rest to slowQueue with slowGetImageForURL:.

Inform the cache that an urgent image fetch is no longer urgent

// Objective-C
[SGImageCache moveTaskToSlowQueueForURL:url];
// Swift
SGImageCache.moveTaskToSlowQueueForURL(url)

This is useful for deprioritising image fetches for content that has scrolled off screen. The content may scroll back on screen later, so you still want the fetch to happen, but it is no longer urgently required.

Perform actions on remote fetch, fail or retry

// Objective-C
SGCachePromise *promise = [SGImageCache getImageForURL:url];
promise.then(^(UIImage *image) {
  self.imageView.image = image;
});
promise.onRetry = ^{
  // Called when SGImageCache automatically retries
  // fetching the image due to a reachability change.
  [self showLoadingSpinner];
};
promise.onFail = ^(NSError *error, BOOL fatal) {
  // If the failure was fatal, SGImageCache will not
  // automatically retry (eg. from a 404)
  [self displayError:error];
};
// Swift
let promise = SGImageCache.getImageForURL(url)
promise.swiftThen({object in
  if let image = object as? UIImage {
      self.imageView.image = image
  }
  return nil
})
promise.onRetry = {
  self.showLoadingSpinner()
}
promise.onFail = { (error: NSError?, wasFatal: Bool) -> () in
  self.displayError(error)
}

This is useful for displaying states of network failure, loading spinners on reachability change, or any other functionality that might need to be notified that an image could not be fetched.

fastQueue

fastQueue is a parallel queue, used for urgently required images. The getImageForURL: method adds tasks to this queue. The maximum number of parallel tasks is managed by iOS, based on the device's number of processors, and other factors.

slowQueue

slowQueue is a serial queue, used for prefetching images that might be required later (eg for currently off screen content). The slowGetImageForURL: method adds tasks to this queue.

slowQueue is automatically suspended while fastQueue is active, to avoid consuming network bandwidth while urgent image fetches are in progress. Once all fastQueue tasks are completed slowQueue will be resumed.

Task Deduplication

If an image is requested for a URL that is already queued or in progress, SGImageCache reuses the existing task, and if necessary will move it from slowQueue to fastQueue, depending on which image fetch method was used. This ensures that there will be only one network request per URL, regardless of how many times it's been asked for.

Intelligent image releasing on memory warning

If you use SGImageView instead of UIImageView, and load the image via one of the setImageForURL: methods, off screen image views will release their image on memory warning, and subsequently restore them from cache if the image view returns to screen. This allows off screen but still existing view controllers (eg a previous controller in a nav controller's stack) to free up memory that would otherwise be unnecessarily retained, and reduce the chances of your app being terminated by iOS in limited memory situations.

Generic caching of NSData

You can use SGImageCache for caching of generic data in the form of an NSData object (eg. PDFs, JSON payloads). Just use the equivalent SGCache class method instead of the SGImageCache one:

// Objective-C
[SGCache getFileForURL:url].then(^(NSData *data) {
  // do something with data
});
// Swift
SGCache.getFileForURL(url).swiftThen({object in
  if let data = object as? NSData {
    // do something with data
  }
  return nil
})

More Repositories

1

fuzzywuzzy

Fuzzy String Matching in Python
Python
9,067
star
2

react-infinite

A browser-ready efficient scrolling container based on UITableView
JavaScript
2,714
star
3

thefuzz

Fuzzy String Matching in Python
Python
2,460
star
4

soulmate

Unmaintained, use Soulheart!
Ruby
1,061
star
5

android-PlacesAutocompleteTextView

An address-autocompleting text field for Android
Java
281
star
6

djjob

PHP port of delayed_job, a database backed asynchronous priority queue
PHP
253
star
7

hashi-helper

Disaster Recovery and Configuration Management for Consul and Vault
Go
184
star
8

nomad-helper

Useful tools for working with @hashicorp Nomad at scale
Go
157
star
9

docker-mirror

Mirror docker images across image repositories
Go
140
star
10

nomad-firehose

Firehose all nomad job, allocation, nodes and evaluations changes to rabbitmq, kinesis or stdout
Go
115
star
11

bash-aptfile

A simple method of defining apt-get dependencies for an application
Shell
89
star
12

businesstime

A simple python utility for calculating business time aware timedeltas between two datetimes
Python
85
star
13

react-slider

DEPRECATED: A Slider in React
JavaScript
80
star
14

docker-build-cacher

Builds a service with docker and caches the intermediate stages
Haskell
53
star
15

druzhba

Python
36
star
16

conductor

A data-backed adwords campaign bidder
Python
25
star
17

backstage-plugins

SeatGeek Backstage Plugins Collection
TypeScript
25
star
18

haldane

a friendly http interface to the aws api
Python
23
star
19

dhall-nomad

Create maintainable nomad job files
Dhall
22
star
20

SGHTTPRequest

Objective-C
17
star
21

aws-dynamic-consul-catalog

Keep your Consul service catalog in sync with your RDS instances
Go
16
star
22

tornado-async-transformer

libcst transformer that replaces tornado's legacy @gen.coroutine syntax with python3.5+ native async/await
Python
15
star
23

amqp-dispatcher

A daemon to run AMQP consumers
Python
14
star
24

statsd_rb

DEPRECATED. Use https://github.com/etsy/statsd instead of this.
Ruby
13
star
25

hell

Deprecated: Hell is an open source web interface that exposes a set of capistrano recipes as a json api, for usage within large teams
JavaScript
12
star
26

redis-health

Can be used to check the health of your Redis instance.
Go
12
star
27

SGAPI

The SG Api SDK for iOS
Objective-C
11
star
28

SGListAnimator

Provides animated transitions for your table and collection views, so you don't have to resort to calling `reloadData`.
Objective-C
10
star
29

api-support

A support channel for the SeatGeek Platform
8
star
30

react-select-option

A plain <select> component that can be styled.
JavaScript
8
star
31

circus-logstash

A Circus logger for shipping logs to Logstash
Python
6
star
32

nomad-crashloop-detector

detect Nomad allocation crash-loops, by consuming the allocation stream from nomad-firehose
Go
5
star
33

gramo

Kotlin
5
star
34

datadog-service-helper

use consul catalog to manage datadog service checks
Go
4
star
35

wrecker-ui

An HTML interface for wrecker, the load testing tool
Elm
4
star
36

graceful_listener

net.Listener implementation for graceful shutdown
Go
4
star
37

sgcli

A command-line interface for SeatGeek
Python
4
star
38

logrus-gelf-formatter

Formats logrus messages in the GELF JSON format
Go
3
star
39

geocoder-java

Fork of https://code.google.com/p/geocoder-java/
Java
3
star
40

homebrew-formulae

Custom SeatGeek Formula for Homebrew
Ruby
3
star
41

k8s-reconciler-generic

A generic Kubernetes reconciler abstraction based on kubebuilder
Go
3
star
42

sgmods-go

Codemods for golang from SeatGeek.
Go
1
star
43

api-intro-presentation

1
star
44

greenhouse-api-client

Kotlin
1
star
45

seatgeek-emea-ios-sdk

Swift
1
star
46

elastic-search-health

Go
1
star
47

vault-stress

Go
1
star
48

sfn-stack-profile

Ruby
1
star
49

eslint-config-seatgeek-react-standard

React rules specific to the SeatGeek repositories.
JavaScript
1
star