Keep Widgets Fresh With Small Shared Snapshots

A widget showing four remaining tasks does not need to load the app’s entire task database, recreate its repositories, and fetch the same records again. The containing app already has the authorized data needed to calculate that count.

Write a small display snapshot and let the widget read it. The interesting parts are deciding when it changed, what stale means, and what happens when the account changes.

Give the widget a narrow contract

This snapshot contains a version, an opaque account key, a count, and the time the source data was observed. It deliberately contains no authentication token or full task content.

import Foundation
import WidgetKit

struct WidgetSnapshot: Codable, Equatable, Sendable {
    let version: Int
    let accountKey: String
    let remainingCount: Int
    let generatedAt: Date
}
enum WidgetRead: Equatable {
    case fresh(WidgetSnapshot)
    case stale(WidgetSnapshot)
    case unavailable
}
func readWidgetSnapshot(_ data: Data, accountKey: String, now: Date) -> WidgetRead {
    guard data.count <= 65_536,
        let value = try? JSONDecoder().decode(WidgetSnapshot.self, from: data),
        value.version == 1, value.accountKey == accountKey,
        value.remainingCount >= 0,
        value.generatedAt <= now.addingTimeInterval(300)
    else { return .unavailable }
    return now.timeIntervalSince(value.generatedAt) > 3_600 ? .stale(value) : .fresh(value)
}
func writeWidgetSnapshot(_ value: WidgetSnapshot, to url: URL) throws -> Bool {
    let encoder = JSONEncoder()
    encoder.outputFormatting = [.sortedKeys]
    let data = try encoder.encode(value)
    guard data.count <= 65_536 else { throw CocoaError(.fileWriteOutOfSpace) }
    if let old = try? Data(contentsOf: url), old == data { return false }
    try data.write(to: url, options: .atomic)
    return true
}

The 64 KiB limit, one-hour stale threshold, and five-minute future-date allowance are example product policies. They are not WidgetKit requirements. The decoder receives Data that is already in memory, so its size check limits accepted input, not the cost of reading the file. Keep file reads bounded too if the source can be larger than this app-owned snapshot.

Use the same account key expected by the current shared account context. A snapshot from another account should become unavailable, not briefly appear while new data loads. The key is a consistency check, not a substitute for authentication or App Group access control.

Publish before requesting a reload

Use the shared container obtained through FileManager with your configured App Group identifier. Have one serialized writer in the app own this file, while the widget reads it.

Apple’s atomic writing option writes an auxiliary file and replaces the original. It prevents the reader from intentionally receiving your half-written JSON. It does not order several competing writers or promise a particular crash-durability level.

After a successful changed write, request the relevant widget kind:

WidgetCenter.shared.reloadTimelines(ofKind: "RemainingTasks")

That string must match the widget configuration’s kind. Calling reload before replacing the file can cause the provider to read the previous snapshot.

Sorted JSON keys make the byte comparison stable for this simple format. The runtime fixture initially exposed unnecessary writes without deterministic ordering. Alternatively, compare decoded values or a deliberate content revision instead of encoded bytes.

Do not set generatedAt to a fresh Date merely because a view appeared. That makes every otherwise identical snapshot different. Update it when the source observation advances, according to the freshness promise you display.

Freshness belongs in the interface

A stale snapshot can still be useful if it says when it was updated. Missing, corrupt, unsupported-version, or wrong-account data needs an unavailable state with a sensible action to open the app.

Do not present a decoding failure as a count of zero. Zero is valid business data and tells the user something different from “the widget could not load its snapshot.”

On sign-out, remove or replace the account’s snapshot and request a reload. Because the system controls rendering, avoid putting sensitive content in the widget’s display contract in the first place. Choose file protection appropriate to the data, and test locked-device access without weakening protection simply to make a test pass.

A reload request is not a deadline

Apple’s widget refresh guidance describes system scheduling and budgets. A reload request does not promise that a visible widget changes immediately.

Use timeline entries for predictable future changes and dynamic date presentation where appropriate. Avoid requesting reloads for every intermediate edit or every row change. Derive one compact snapshot after the meaningful model update, then compare it before writing.

This client-derived count needs no new server aggregate or scheduled function. If a future requirement needs authoritative data while the app is closed, assess that separately rather than adding server infrastructure to duplicate a count the client already knows.

September 2026 review: freshness, account mismatch, malformed data, atomic local writing, and unchanged-write suppression passed. The example type-checked for iOS 17; actual App Group permissions, locked-device behavior, and WidgetKit reload timing were not exercised.