/74f724a56b79d6829d
Created 4 months ago...
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
struct Provider: TimelineProvider {
func placeholder(in context: Context) -> SpeciesEntry {
SpeciesEntry(date: Date(), species: Species.sample)
}
func getSnapshot(in context: Context, completion: @escaping (SpeciesEntry) -> ()) {
let entry = SpeciesEntry(date: Date(), species: Species.sample)
completion(entry)
}
@MainActor
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
guard let container = try? ModelContainer(for: Species.self, Family.self) else {
let entry = SpeciesEntry(date: Date(), species: nil)
let timeline = Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(60 * 5)))
completion(timeline)
return
}
let descriptor = FetchDescriptor<Species>()
let speciesList = (try? container.mainContext.fetch(descriptor)) ?? []
let randomSpecies = speciesList.randomElement()
let entry = SpeciesEntry(date: Date(), species: randomSpecies)
let timeline = Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(60 * 5)))
completion(timeline)
}
}
struct SpeciesEntry: TimelineEntry {
var date: Date
let species: Species?
}
struct Okla_WidgetsEntryView : View {
var entry: Provider.Entry
var body: some View {
HStack(alignment: .top) {
if let species = entry.species {
Image(species.imageName)
.resizable()
.aspectRatio(contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 8))
VStack(alignment: .leading) {
Text(species.scientificName)
.bold()
Text("\"\(species.commonName)\"")
.italic()
.opacity(0.6)
}
} else {
Text("Unable to get species information.")
}
}
}
}
struct Okla_Widgets: Widget {
let kind: String = "Random_Species_Widget"
var body: some WidgetConfiguration {
let provider = Provider()
return StaticConfiguration(kind: kind, provider: provider) { entry in
Okla_WidgetsEntryView(entry: entry)
.containerBackground(.fill.tertiary, for: .widget)
.modelContainer(for: [Species.self, Family.self])
}
.configurationDisplayName("Random Species")
.description("Show a random Occlupanid species.")
.supportedFamilies([.systemSmall, .systemMedium])
}
}
#Preview(as: .systemMedium) {
Okla_Widgets()
} timeline: {
SpeciesEntry(date: .now, species: Species.sample)
}