How to Fetch and Show Remote Data on a Widget?

Lee Kah Seng
5 min readFeb 1

This article is originally published at

When creating widgets for your apps, sometimes it might be sufficient to just display data that is locally generated. However, in most cases, we will want our widgets to display data that is fetched from a remote server.

In this article, let’s explore this topic. We will create a sample widget that can make a RESTful API call, download an image, and then show it on the widget. There are a lot of grounds to cover, so let’s begin!

The Doggy Widget 🐶

The widget we are going to create is called Doggy Widget. It is a simple widget that shows you random dog images all day long.

The Doggy Widget in action

We will use Dog API as our widget’s remote server. Calling the API will give us the following JSON response that contains a random dog image URL:

"status": "success",
"message": ""

The Doggy Widget will call the API every 15 minutes. Once the image is downloaded, we will cache it locally and show it on the widget.

The Doggy Fetcher

First thing first, let’s create a fetcher class that calls the API and download the dog image.

struct Doggy: Decodable {
let message: URL
let status: String

struct DoggyFetcher {

enum DoggyFetcherError: Error {
case imageDataCorrupted

/// The path where the cached image located
private static var cachePath: URL {
URL.cachesDirectory.appending(path: "doggy.png")

/// The cached dog image
static var cachedDoggy: UIImage? {
guard let imageData = try? Data(contentsOf: cachePath) else {
return nil
return UIImage(data: imageData)

/// Is cached image currently available
static var cachedDoggyAvailable: Bool {
cachedDoggy != nil

/// Call the Dog API and then download and cache the dog image
static func fetchRandomDoggy() async throws -> UIImage {

let url =…
Lee Kah Seng

Support me by becoming a Medium member: ⦿ 🇲🇾 Creator of ⦿ iOS developer since 2011