Skip to content

Instantly share code, notes, and snippets.

@apatronl
Last active July 30, 2020 17:25
Show Gist options
  • Save apatronl/46ce981e2e0ed686975bc8bbc74861c1 to your computer and use it in GitHub Desktop.
Save apatronl/46ce981e2e0ed686975bc8bbc74861c1 to your computer and use it in GitHub Desktop.
import SwiftUI
import WidgetKit
struct RandomEmojiWidgetProvider: TimelineProvider {
public func snapshot(with context: Context, completion: @escaping (RandomEmojiEntry) -> ()) {
let entry = RandomEmojiEntry(date: Date(), emojiDetails: EmojiProvider.random())
completion(entry)
}
public func timeline(
with context: Context,
completion: @escaping (Timeline<RandomEmojiEntry>) -> ()
) {
var entries: [RandomEmojiEntry] = []
// Generate a timeline consisting of five entries an hour apart, starting from the current date.
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = RandomEmojiEntry(date: entryDate, emojiDetails: EmojiProvider.random())
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
struct RandomEmojiEntry: TimelineEntry {
public let date: Date
public let emojiDetails: EmojiDetails
}
struct RandomEmojiWidgetEntryView: View {
var entry: RandomEmojiWidgetProvider.Entry
var body: some View {
EmojiWidgetView(emojiDetails: entry.emojiDetails)
}
}
@main
struct RandomEmojiWidget: Widget {
private let kind: String = "RandomEmojiWidget"
public var body: some WidgetConfiguration {
StaticConfiguration(
kind: kind,
provider: RandomEmojiWidgetProvider(),
placeholder: EmojiWidgetPlaceholderView()
) { entry in
RandomEmojiWidgetEntryView(entry: entry)
}
.configurationDisplayName("Random Emoji Widget")
.description("Display a widget with an emoji that is updated randomly.")
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment