Created
December 22, 2021 12:17
-
-
Save maiyama18/cd2695a87e30aae716f1a2c3f386a1b5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import WidgetKit | |
import SwiftUI | |
struct RandomNumberWidgetProvider: IntentTimelineProvider { | |
func placeholder(in context: Context) -> RandomNumberWidgetEntry { | |
RandomNumberWidgetEntry(date: Date(), number: 42) | |
} | |
func getSnapshot(for configuration: RandomNumberIntent, in context: Context, completion: @escaping (RandomNumberWidgetEntry) -> ()) { | |
let entry = RandomNumberWidgetEntry(date: Date(), number: getRandomNumber(configuration: configuration)) | |
completion(entry) | |
} | |
func getTimeline(for configuration: RandomNumberIntent, in context: Context, completion: @escaping (Timeline<RandomNumberWidgetEntry>) -> ()) { | |
var entries: [RandomNumberWidgetEntry] = [] | |
let currentDate = Date() | |
for hourOffset in 0 ..< 5 { | |
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)! | |
let entry = RandomNumberWidgetEntry(date: entryDate, number: getRandomNumber(configuration: configuration)) | |
entries.append(entry) | |
} | |
let timeline = Timeline(entries: entries, policy: .atEnd) | |
completion(timeline) | |
} | |
private func getRandomNumber(configuration: RandomNumberIntent) -> Int { | |
let maxNumber = configuration.maxNumber?.intValue ?? 100 | |
return Int.random(in: 1...maxNumber) | |
} | |
} | |
struct RandomNumberWidgetEntry: TimelineEntry { | |
let date: Date | |
let number: Int | |
} | |
struct RandomNumberWidgetEntryView : View { | |
var entry: RandomNumberWidgetProvider.Entry | |
var body: some View { | |
VStack { | |
Text("\(entry.number)") | |
.font(.largeTitle) | |
Text(entry.date, style: .time) | |
} | |
} | |
} | |
@main | |
struct Widgets: Widget { | |
let kind: String = "Widgets" | |
var body: some WidgetConfiguration { | |
IntentConfiguration(kind: kind, intent: RandomNumberIntent.self, provider: RandomNumberWidgetProvider()) { entry in | |
RandomNumberWidgetEntryView(entry: entry) | |
} | |
.configurationDisplayName("Random Number Widget") | |
.description("This widget shows random number") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment