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-04-01 12:10:59 +02:00
|
|
|
|
2023-03-11 18:30:33 +01:00
|
|
|
import WidgetKit
|
|
|
|
import SwiftUI
|
|
|
|
import Intents
|
|
|
|
|
2023-05-01 07:50:24 +02:00
|
|
|
struct QRCodeProvider: TimelineProvider {
|
|
|
|
typealias Entry = QRCodeWidgetEntry
|
2023-03-11 18:30:33 +01:00
|
|
|
|
2023-05-01 07:50:24 +02:00
|
|
|
func placeholder(in context: Context) -> QRCodeWidgetEntry {
|
|
|
|
AccountFetcher.shared.placeholder()
|
2023-03-11 18:30:33 +01:00
|
|
|
}
|
|
|
|
|
2023-05-01 07:50:24 +02:00
|
|
|
func getSnapshot(in context: Context, completion: @escaping (QRCodeWidgetEntry) -> Void) {
|
2023-03-11 18:30:33 +01:00
|
|
|
Task {
|
2023-05-01 07:50:24 +02:00
|
|
|
if let widgetEntry = await self.getWidgetEntry().first {
|
2023-03-11 18:30:33 +01:00
|
|
|
completion(widgetEntry)
|
|
|
|
} else {
|
2023-05-01 07:50:24 +02:00
|
|
|
let entry = AccountFetcher.shared.placeholder()
|
2023-03-11 18:30:33 +01:00
|
|
|
completion(entry)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-01 12:10:59 +02:00
|
|
|
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
|
2023-03-11 18:30:33 +01:00
|
|
|
Task {
|
|
|
|
let currentDate = Date()
|
2023-05-01 07:50:24 +02:00
|
|
|
let widgetEntries = await self.getWidgetEntry()
|
2023-04-01 12:10:59 +02:00
|
|
|
|
2023-05-01 07:50:24 +02:00
|
|
|
let nextUpdateDate = Calendar.current.date(byAdding: .day, value: 1, to: currentDate)!
|
2023-03-11 18:30:33 +01:00
|
|
|
let timeline = Timeline(entries: widgetEntries, policy: .after(nextUpdateDate))
|
|
|
|
completion(timeline)
|
|
|
|
}
|
|
|
|
}
|
2023-04-01 12:10:59 +02:00
|
|
|
|
2023-05-01 07:50:24 +02:00
|
|
|
func getWidgetEntry() async -> [QRCodeWidgetEntry] {
|
2023-03-11 18:30:33 +01:00
|
|
|
do {
|
2023-05-01 07:50:24 +02:00
|
|
|
return try await AccountFetcher.shared.fetchWidgetEntry()
|
2023-03-11 18:30:33 +01:00
|
|
|
} catch {
|
2023-05-01 07:50:24 +02:00
|
|
|
return [AccountFetcher.shared.placeholder()]
|
2023-03-11 18:30:33 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|