I have a widget with a SwiftUI Text
timer date. It countdowns as expected. However, when the device is locked, the timer is frozen.
To reproduce it, add the SwiftUI Text(_:style:)
view to a widget and place the widget on the "Today View". The countdown should work as expected. However, lock the phone then view the Today View in a locked state. The timer is frozen.
Below is the full working sample code:
import WidgetKit
import SwiftUI
struct Provider: TimelineProvider {
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date())
}
func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
let entry = SimpleEntry(date: Date())
completion(entry)
}
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
var entries: [SimpleEntry] = []
// 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 = SimpleEntry(date: entryDate)
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
struct SimpleEntry: TimelineEntry {
let date: Date
}
struct TestWidget123EntryView : View {
var entry: Provider.Entry
var body: some View {
Text(entry.date, style: .timer)
.multilineTextAlignment(.center)
.padding()
}
}
@main
struct TestWidget123: Widget {
let kind: String = "TestWidget123"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: Provider()) { entry in
TestWidget123EntryView(entry: entry)
}
.configurationDisplayName("My Widget")
.description("This is an example widget.")
}
}
struct TestWidget123_Previews: PreviewProvider {
static var previews: some View {
TestWidget123EntryView(entry: SimpleEntry(date: Date()))
.previewContext(WidgetPreviewContext(family: .systemSmall))
}
}
I don't have any data protected data and I tried using a timer but didn't work at all. How can I allow the Text
timer to countdown in a locked state?