I am creating a widget using WidgetKit to display the iPhone battery level.
I setup the following timeline to update the widget very minute. (I use one minute for testing the app. Once it works I'll use five minutes to preserve resources.)
In the "View" I display the time and battery level. The time is updated every minute. However, the battery level does not get updated.
func getTimeline(in context: Context, completion: @escaping (Timeline) -> ()) {
var entries: [SimpleEntry] = []
let currentDate = Date()
let updateInterval = 1
for minuteOffset in stride(from: 0, to: 60, by: updateInterval ) {
let entryDate = Calendar.current.date( byAdding: .minute, value: minuteOffset, to: currentDate )!
let entry = SimpleEntry( date: entryDate )
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
} // func
var body: some View {
let _ = UIDevice.current.isBatteryMonitoringEnabled = true
let batteryLevel = UIDevice.current.batteryLevel
VStack {
Text(entry.date, style: .time)
let str = String( format: "%.0f%%", batteryLevel * 100.0 )
Text( str )
}
} // some View