Keep a battery iOS widget updated

Viewed 647

i'm working on a battery widget but have problems updating the battery level often enough. I Would love to update the widget every time the battery percentage changes. But from all the reading i have done, this looks to be impossible. I tried requesting a new timeline both every 5 min and every 15 min with no luck. I see some apps on the AppStore have a battery indicator and it updates quite often. Any clues to have they accomplishes this? I see some people talking about using background fetch. That can't be the best way? I have included my code, maybe i have implemented it wrong? Tanks for any feedback on this!

Provider

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>) -> ()) {
        let currentDate = Date()
        let newDate = Calendar.current.date(byAdding: .minute, value: 15, to: currentDate)

        let timeline = Timeline(entries: [SimpleEntry(date: currentDate)], policy: .after(newDate!))
        completion(timeline)
    }
}

BatteryWidgetEntryView

struct BatteryWidgetEntryView : View {
    var entry: Provider.Entry

    var body: some View {
        Text("\(Int(Self.battery * 100))")
            .font(.largeTitle)
    }
    
    static let battery: Float = {
        UIDevice.current.isBatteryMonitoringEnabled = true
        let batteryLvl = UIDevice.current.batteryLevel
        return batteryLvl
    }()
}
1 Answers

You can't do it from the Widget, you have to reload the timeline from the host app. Host app to monitor the battery status and call

WidgetCenter.shared.reloadTimelines(ofKind: "com.mybattery.widget")

To trigger the reload for the widget.

Related