I’m making an app to keep track of values across a list of trends. Part of it is to have clickers on the phone home screen to increase the trend value. With widgets now being configurable, I want the user to be able to choose which trend to see.
I was able to set it up so that an app intent handles the increment in the widget body. Then, I was able to get it to a state for the user to switch between there trends, but the issue arises when the user goes in the app and puts a new trend in the list or takes one out. The list in the widget isnt updating to reflect this and showing whatever list existed at build time.
Here’s my provider code:
struct TrendTimelineProvider: AppIntentTimelineProvider {
func timeline(for configuration: SelectClickerTrendsIntent, in context: Context) async -> Timeline {
Timeline(entries:
[TrendEntry(date: Date(), trend: getTrend(for: configuration.trend.id))],
policy: .atEnd)
}
func snapshot(for configuration: SelectClickerTrendsIntent, in context: Context) async -> TrendEntry {
return TrendEntry(date: Date(), trend: configuration.trend)
}
func placeholder(in context: Context) -> TrendEntry {
return TrendEntry(date: .now, trend: TrendData(blockType: ""))
}
func getTrend(for uuid: UUID) -> TrendData {
if let store = UserDefaults(suiteName: suiteName),
let data = store.data(forKey: storageKey),
let trends = try? JSONDecoder().decode([TrendData].self, from: data) {
// Find the trend with the specified UUID
if let selectedTrend = trends.first(where: { $0.id == uuid }) {
return selectedTrend
}
}
return TrendData(blockType: "")
}
}
struct SelectClickerTrendsIntent: WidgetConfigurationIntent {
static var title: LocalizedStringResource = “Clicker Trend Selection”
static var description: IntentDescription? = IntentDescription(“Select a clicker trend to show”)
@Parameter(title: "Clicker Trends")
var trend: TrendData
}
struct TrendDataQuery: EntityQuery {
public func entities(for identifiers: [TrendData.ID]) async throws -> [TrendData] {
return TrendData.allClicker.filter { identifiers.contains($0.id) }
}
public func suggestedEntities() async throws -> [TrendData] {
return TrendData.allClicker
}
public func defaultResult() async -> TrendData? {
return TrendData.allClicker.first
}
}
struct TrendData: Identifiable, Codable, Equatable, Hashable, AppEntity {
…
public static var typeDisplayRepresentation: TypeDisplayRepresentation = “Trends”
public static var defaultQuery = TrendDataQuery()
public var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "(title)")
}
…
}
** Notes:
- “trend: getTrend(for: configuration.trend.id))” was the only way i could get the buttons to actually update in the widget when they get clicked.
- I have two types of trends and ones called clicker hence “allClicker”.
Jeremy Gavrilov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.