-
-
Notifications
You must be signed in to change notification settings - Fork 285
Expand file tree
/
Copy pathWidget.swift
More file actions
69 lines (59 loc) · 2.23 KB
/
Copy pathWidget.swift
File metadata and controls
69 lines (59 loc) · 2.23 KB
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
// Scaffold generated by home_widget. Adjust the widget for your needs.
import SwiftUI
import WidgetKit
private let appGroupId = "group.es.antonborri.exampleHomeWidget"
private let imageKey = "image"
struct Provider: TimelineProvider {
func placeholder(in context: Context) -> ImageWidgetHomeWidgetEntry {
ImageWidgetHomeWidgetEntry(date: Date(), imagePath: nil)
}
func getSnapshot(in context: Context, completion: @escaping (ImageWidgetHomeWidgetEntry) -> Void)
{
completion(ImageWidgetHomeWidgetEntry(date: Date(), imagePath: Self.resolvedImagePath()))
}
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
let entry = ImageWidgetHomeWidgetEntry(date: Date(), imagePath: Self.resolvedImagePath())
completion(Timeline(entries: [entry], policy: .atEnd))
}
private static func resolvedImagePath() -> String? {
let prefs = UserDefaults(suiteName: appGroupId)
guard let path = prefs?.string(forKey: imageKey), !path.isEmpty else { return nil }
guard FileManager.default.fileExists(atPath: path) else { return nil }
return path
}
}
struct ImageWidgetHomeWidgetEntry: TimelineEntry {
let date: Date
/// Absolute path to the PNG written by home_widget; nil if missing or not on disk.
let imagePath: String?
}
struct ImageWidgetHomeWidgetEntryView: View {
var entry: Provider.Entry
var body: some View {
GeometryReader { geo in
ZStack {
Color.white
if let path = entry.imagePath, let uiImage = UIImage(contentsOfFile: path) {
Image(uiImage: uiImage)
.resizable()
.scaledToFit()
.frame(width: geo.size.width, height: geo.size.height)
} else {
Text("Open App to save Image")
.multilineTextAlignment(.center)
.foregroundColor(Color.secondary)
.frame(width: geo.size.width, height: geo.size.height, alignment: .center)
}
}
}
}
}
struct ImageWidgetHomeWidget: Widget {
let kind: String = "ImageWidgetHomeWidget"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: Provider()) { entry in
ImageWidgetHomeWidgetEntryView(entry: entry)
}
.configurationDisplayName("ImageWidgetHomeWidget")
}
}