forked from ABausG/home_widget
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HomeWidgetExample.swift
71 lines (60 loc) · 2.27 KB
/
HomeWidgetExample.swift
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
//
// HomeWidgetExample.swift
// HomeWidgetExample
//
// Created by Anton Borries on 04.10.20.
//
import WidgetKit
import SwiftUI
private let widgetGroupId = "YOUR_APP_GROUP_ID"
struct Provider: TimelineProvider {
func placeholder(in context: Context) -> ExampleEntry {
ExampleEntry(date: Date(), title: "Placeholder Title", message: "Placeholder Message")
}
func getSnapshot(in context: Context, completion: @escaping (ExampleEntry) -> ()) {
let data = UserDefaults.init(suiteName:widgetGroupId)
let entry = ExampleEntry(date: Date(), title: data?.string(forKey: "title") ?? "No Title Set", message: data?.string(forKey: "message") ?? "No Message Set")
completion(entry)
}
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
getSnapshot(in: context) { (entry) in
let timeline = Timeline(entries: [entry], policy: .atEnd)
completion(timeline)
}
}
}
struct ExampleEntry: TimelineEntry {
let date: Date
let title: String
let message: String
}
struct HomeWidgetExampleEntryView : View {
var entry: Provider.Entry
let data = UserDefaults.init(suiteName:widgetGroupId)
var body: some View {
VStack.init(alignment: .leading, spacing: /*@START_MENU_TOKEN@*/nil/*@END_MENU_TOKEN@*/, content: {
Text(entry.title).bold().font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/)
Text(entry.message)
.font(.body)
.widgetURL(URL(string: "homeWidgetExample://message?message=\(entry.message)&homeWidget"))
}
)
}
}
@main
struct HomeWidgetExample: Widget {
let kind: String = "HomeWidgetExample"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: Provider()) { entry in
HomeWidgetExampleEntryView(entry: entry)
}
.configurationDisplayName("My Widget")
.description("This is an example widget.")
}
}
struct HomeWidgetExample_Previews: PreviewProvider {
static var previews: some View {
HomeWidgetExampleEntryView(entry: ExampleEntry(date: Date(), title: "Example Title", message: "Example Message"))
.previewContext(WidgetPreviewContext(family: .systemSmall))
}
}