Vernissage/VernissageWidget/Provider.swift

48 lines
1.4 KiB
Swift
Raw Normal View History

2023-03-11 18:30:33 +01:00
//
// https://mczachurski.dev
// Copyright © 2023 Marcin Czachurski and the repository contributors.
2023-03-28 10:35:38 +02:00
// Licensed under the Apache License 2.0.
2023-03-11 18:30:33 +01:00
//
2023-03-11 18:30:33 +01:00
import WidgetKit
import SwiftUI
import Intents
struct Provider: TimelineProvider {
typealias Entry = WidgetEntry
func placeholder(in context: Context) -> WidgetEntry {
ImageFetcher.shared.placeholder()
}
func getSnapshot(in context: Context, completion: @escaping (WidgetEntry) -> Void) {
2023-03-11 18:30:33 +01:00
Task {
if let widgetEntry = await self.getWidgetEntries(length: 1).first {
completion(widgetEntry)
} else {
let entry = ImageFetcher.shared.placeholder()
completion(entry)
}
}
}
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
2023-03-11 18:30:33 +01:00
Task {
let currentDate = Date()
let widgetEntries = await self.getWidgetEntries()
2023-04-10 12:35:49 +02:00
let nextUpdateDate = Calendar.current.date(byAdding: .hour, value: 1, to: currentDate)!
2023-03-11 18:30:33 +01:00
let timeline = Timeline(entries: widgetEntries, policy: .after(nextUpdateDate))
completion(timeline)
}
}
2023-04-10 12:35:49 +02:00
func getWidgetEntries(length: Int = 3) async -> [WidgetEntry] {
2023-03-11 18:30:33 +01:00
do {
return try await ImageFetcher.shared.fetchWidgetEntries(length: length)
} catch {
return [ImageFetcher.shared.placeholder()]
}
}
}