---
title: "#156: Caching with AwesomeCache 🗃"
url: https://littlebitesofcocoa.com/156-caching-with-awesomecache
author: Jake Marsh
published: 2015-12-28
topics: ["Libraries","Techniques"]
description: "Today we'll check out a library called AwesomeCache by Alexander Schuch that caches data in-memory and on disk."
---

# #156: Caching with AwesomeCache 🗃

By Jake Marsh, December 28, 2015. HTML: https://littlebitesofcocoa.com/156-caching-with-awesomecache

Today we'll check out a library called [AwesomeCache](https://github.com/aschuch/AwesomeCache) by [Alexander Schuch](https://github.com/aschuch) that caches data in-memory <i>and</i> on disk. Let's do it.

_AwesomeCache_ can be interacted with in a few different ways. Let's start by creating a **cache**:

``` swift
let cache = try! Cache<NSString>(name: "photos")
```

We can store **values** in the **cache** like this:

``` swift
cache.setObject(
  responseString, 
  forKey: "a-unique-cache-key",
  expires: .Seconds(300)
)
```

If we're not setting an **expiration time**, we can use this shorthand:

``` swift
cache["a-unique-cache-key"] = "Hello"
```

We can retrieve **values** from the **cache** in a similar way:

``` swift
let cachedResponse = cache["photos.all"]
```

One of the handiest features of _AwesomeCache_ is how it can help cache API responses (or any async code really). Here's how it works:

``` swift
cache.setObjectForKey("photos.all", cacheBlock: { success, failure in
  self.requestLatestPhotos({ response in
    success(response, .Seconds(300))
  }, failure: { error in
    failure(error)
  })
}, completion: { object, isLoadedFromCache, error in
  if let object = object {
    // object is now cached, and ready to use
  }
})
```

If a **value** already exists in the **cache** for the given **key**, the `completion`** closure** is called right away. Otherwise, the `cacheBlock` **closure** is called. Inside the `cacheBlock` we call our custom own API code, then tell _AwesomeCache_ if we succeeded or failed.

More info about _AwesomeCache_ can be found at [git.io/awesomecache](http://git.io/awesomecache)
