Search code examples
iosswiftbackgroundfetchbattery

Battery state and level thanks to the background fetch?


I want to know when the user of the app plug or unplug his phone's charger even when the app is in the background. I can do that with the NetworkReachability (wifi, ondata, not-reachable, not determine...) but not with the battery level or the battery state. I can know the battery level and the battery state only when the app is in the foreground or active unlike when she's in the background.

Can I set a background fetch for the battery level(or state)? If the user unplug his charger, I would launch a function or a print (or whatever).

Can I set listeners on the battery level or state ? Because that's how I did for the NetworkReachability but I found only observers available for the battery characteristics.

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if let a = window?.rootViewController as? UIViewController{
            UIDevice.current.isBatteryMonitoringEnabled = true
            NotificationCenter.default.addObserver(self, selector: #selector(self.batteryStateDidChange), name: .UIDeviceBatteryStateDidChange, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(self.batteryLevelDidChange), name: .UIDeviceBatteryLevelDidChange, object: nil)
            completionHandler(.newData)
        }

    else{
        completionHandler(.noData)
    }

And it seems like observers don't work with the background fetch or I'm conding wrong ?

I'm really thankful for your help, have a nice day everybody!


Solution

  • Based on the accepted answer, it looks like it wasn't the case, but often these types of questions boil down to trying to defer/cancel intensive, but otherwise discretionary work. If that happens to be the case, I've had great luck with using the NSProcessInfo low power APIs. There's even a notification for when it becomes enabled, which is particularly useful for cancellation.