Melodic Caching for Swift

Overview

Logo

platform license

Johnny is a generic caching library written for Swift 4.

Features

Johnny can cache any model object that conforms to the Cachable protocol.

  • Out-of-the-box support:
    • String, Bool, Int, UInt, Int64, UInt64, Float, Double
    • URL, Data, Date
    • UIImage, UIColor by wrapping them in an Image or Color wrapper class respectively
    • Arrays, Dictionaries and Sets of the above
  • Multiplatform, supporting iOS, macOS, tvOS & watchOS
  • First-level memory cache using NSCache
  • Second-level LRU disk cache
  • Disk access in background thread (always when saving, optionally when fetching)
  • Syncronous & Asynchronous API support
  • Automatic cache eviction on memory warnings & disk capacity reached
  • Unit tested
  • Concise, well-structured code to encourage contributions

Extra ❤️ for images:

  • func setImageWithURL extension on UIImageView, UIButton & NSImageView, optimized for cell reuse

Usage

Caching

Johnny.cache(user, key: "LocalUser")

let imgage = UIImage(named: "awesomeness")
Johnny.cache(Image(image), key: "Image") // Caching a UIImage. UIColor objects must be wrapped in the Color wrapper class the same way.

// You can flag a value to be stored in the Library instead of the Caches folder if you don't want it to be automatically purged:
Johnny.cache(Date(), key: "FirstStart", library: true)

Pulling

// The type of the retrived value must be explicitly stated for the compiler.
let date: Date? = Johnny.pull("FirstStart")

// If you know you are retrieving a large object (> 1.5 MB) you can do it asynchronously
Johnny.pull("4KImage") { (image: Image?) in
    let img = image.uiImage()
}

Removing

Johnny.remove("LocalUser")

Examples

Collections

You can cache any collection of items conforming to the Storable protocol (most standard library data types already do)

let array: [String] = ["Folsom", "Prison", "Blues"]
let stringSet: Set<String> = ["I've", "been", "everywhere"]
// In case of dictionaries, the value must explicitly conform to Storable (so [String: AnyObject] does not work, while [String: Double] does)
let dictionary: [String: String] = ["first": "Solitary", "second": "man"]

Johnny.cache(array, key: "folsom")
Johnny.cache(stringSet, key: "everywhere")
Johnny.cache(dictionary, key: "solitary")

Custom types

Due to current Swift limitations, since the Storable protocol has an associatedType, conformance must be added through an extension. class User: Storable will not work.

struct User {
    
    enum Badassery: String { case Total }
    
    var name: String?
    var uid: Int
    var badassery: Badassery
}


extension User: Storable {
typealias Result = User

static func fromData(data: NSData) -> User.Result? {
    let dict = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as! [NSObject: AnyObject]

    let user = User()
    user.uid = dict["identification"] as! Int
    user.name = dict["name"] as? String
    user.badassery = Badassery(rawValue: dict["badassery"] as! String)!
    return user
}

func toData() -> NSData {
    let json = ["identification": uid, "name": name, "badassery": badassery.rawValue]
    return try! NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions())
    }
}

Using it with Johnny:

let lily = User(name: "Lily", uid: 84823682, badassery: .Total)
Johnny.cache(lily, key: "Lily")

let cachedLily: User = Johnny.pull("Lily")

Requirements

  • iOS 8.0+
  • macOS 10.10+
  • tvOS 9.0+
  • watchOS 2.0+
  • Swift 4.0

Install

CocoaPods

pod 'Johnny'

Carthage

github "zolomatok/Johnny"

Manual

  • Clone the project
  • Select the scheme (platform) and build
  • Drag Johnny.framework to your project
  • In the project settings under your target's General tab, scroll down and add Johhny to the Embedded Binaries section if it's not already added.

Attribution

I'd like to thank the creators of Pantry and Haneke as those projects provided much of the inspiration and some code. Johnny was dreamed up to be the best of both worlds.

License

Johnny is released under the MIT license. See LICENSE for details.

You might also like...
A simple cache that can hold anything, including Swift items

CacheIsKing CacheIsKing is a simple cache that allows you to store any item, including objects, pure Swift structs, enums (with associated values), et

SwiftyCache is a dynamic and auto-managed cache written in Swift
SwiftyCache is a dynamic and auto-managed cache written in Swift

SwiftyCache is a dynamic and auto-managed cache written in Swift. Unlike a simple cache system, it allows you to keep some data even in different executions. Guaranteeing persistence, when desired, without increasing the time required to save or recover data.

iOS Swift Pazarama Bootcamp Week 3 task - App by builded with iTunes Api
iOS Swift Pazarama Bootcamp Week 3 task - App by builded with iTunes Api

MeTunes! a library for itunes! MeTunes. Key Features • Installation • Download • Technologies Used • Credits • License Key Features Fully Programmatic

CachyKit - A Caching Library is written in Swift that can cache JSON, Image, Zip or AnyObject with expiry date/TTYL and force refresh.
CachyKit - A Caching Library is written in Swift that can cache JSON, Image, Zip or AnyObject with expiry date/TTYL and force refresh.

Nice threadsafe expirable cache management that can cache any object. Supports fetching from server, single object expire date, UIImageView loading etc.

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

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

🍁🥓 Lightweight and fast Swift library for image downloading, caching and transformations
🍁🥓 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

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

A high-performance image library for downloading, caching, and processing images in Swift.
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

📱  A strongly-typed, caching GraphQL client for iOS, written in Swift.
📱  A strongly-typed, caching GraphQL client for iOS, written in Swift.

Apollo iOS is a strongly-typed, caching GraphQL client, written in Swift. It allows you to execute queries and mutations against a GraphQL server, and

Swift caching library

Cache A generic caching library for Swift. Cache depends on Foundation. This is still very much a work in progress. Usage Cache provides a simple Cach

Easy HTTP Networking in Swift a NSURLSession wrapper with image caching support
Easy HTTP Networking in Swift a NSURLSession wrapper with image caching support

Networking was born out of the necessity of having a simple networking library that doesn't have crazy programming abstractions or uses the latest rea

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

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

iOS Offline Caching for Web Content

Mattress A Swift framework for storing entire web pages into a disk cache distinct from, but interoperable with, the standard NSURLCache layer. This i

A caching and consistency solution for immutable models.

🚀 Data Rocket Data is a model management system with persistence for immutable models. Motivation Immutability has many benefits, but keeping models

📽 A video player for SwiftUI, support for caching, preload and custom control view.
📽 A video player for SwiftUI, support for caching, preload and custom control view.

Features QuickStart Advances Installation Requirements License Demo Clone or download the project. In the terminal, run swift package resolve. Open Vi

Advanced framework for loading, caching, processing, displaying and preheating images.
Advanced framework for loading, caching, processing, displaying and preheating images.

Advanced framework for loading, caching, processing, displaying and preheating images. This framework is no longer maintained. Programming in Swift? C

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

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

iOS app built with UIKit and programatic auto-layouts to learn and apply knowledge. Offline storage using CoreData and Caching

PurpleImage Search Pixabay for images and save them offline to share and view To use: Clone the GitHub project, build and run in Xcode. The API is com

Comments
  • Manual Installation

    Manual Installation

    CocoaPods and Carthage are awesome tools and make our life really easier, but there are some devs who still don't know how to use them.

    It would be cool to add the Manual installation guide in your README.md. You can take a look at my iOS Readme Template to see how you can do it.

    opened by lfarah 1
Owner
Zoltán Matók
Zoltán Matók
Swift caching library

Cache A generic caching library for Swift. Cache depends on Foundation. This is still very much a work in progress. Usage Cache provides a simple Cach

Sam Soffes 210 Sep 9, 2022
iOS Offline Caching for Web Content

Mattress A Swift framework for storing entire web pages into a disk cache distinct from, but interoperable with, the standard NSURLCache layer. This i

BuzzFeed 522 Oct 25, 2022
A caching and consistency solution for immutable models.

?? Data Rocket Data is a model management system with persistence for immutable models. Motivation Immutability has many benefits, but keeping models

Peter Livesey 652 Nov 11, 2022
Awesome Cache Delightful on-disk cache (written in Swift). Backed by NSCache for maximum performance

Awesome Cache Delightful on-disk cache (written in Swift). Backed by NSCache for maximum performance and support for expiry of single objects. Usage d

Alexander Schuch 1.3k Dec 29, 2022
Cachyr A typesafe key-value data cache for iOS, macOS, tvOS and watchOS written in Swift.

Cachyr A typesafe key-value data cache for iOS, macOS, tvOS and watchOS written in Swift. There already exists plenty of cache solutions, so why creat

Norsk rikskringkasting (NRK) 124 Nov 24, 2022
Carlos - A simple but flexible cache, written in Swift for iOS 13+ and WatchOS 6 apps.

Carlos A simple but flexible cache, written in Swift for iOS 13+ and WatchOS 6 apps. Breaking Changes Carlos 1.0.0 has been migrated from PiedPiper de

National Media & Tech 628 Dec 3, 2022
MemoryCache - type-safe, thread-safe memory cache class in Swift

MemoryCache is a memory cache class in swift. The MemoryCache class incorporates LRU policies, which ensure that a cache doesn’t

Yusuke Morishita 74 Nov 24, 2022
A lightweight generic cache for iOS written in Swift with extra love for images.

Haneke is a lightweight generic cache for iOS and tvOS written in Swift 4. It's designed to be super-simple to use. Here's how you would initalize a J

Haneke 5.2k Dec 29, 2022
Track is a thread safe cache write by Swift. Composed of DiskCache and MemoryCache which support LRU.

Track is a thread safe cache write by Swift. Composed of DiskCache and MemoryCache which support LRU. Features Thread safe: Implement by dispatch_sema

Cheer 268 Nov 21, 2022
A document-based app in Swift Playgrounds 4 for iPad

A document-based SwiftUI app in Swift Playgrounds This sample project demonstrat

Guilherme Rambo 25 Nov 21, 2022