-1

When my app is first launched, the battery level is correctly retrieved by float batteryLevel = [UIDevice currentDevice].batteryLevel. However, when I try to retrieve it later on in my code, I always get the same value even if the battery level changed.

Subsequent calls to [UIDevice currentDevice].batteryLevel always return the same result as the first one, for example: if the battery level was 30% when my app was launched, 10minutes later when I try to retrieve it again, I get 30% as well, but in reality, the battery level is 40% at this point.

Does anyone have any idea why might this happen?

jscs
  • 63,694
  • 13
  • 151
  • 195
Wakeen
  • 1
  • title changed, grammar fixed – Dávid Pásztor Aug 11 '17 at 14:24
  • Have you set `batteryMonitoringEnabled` to `YES`? otherwise you won't be able to see the *changes*. See [`batteryMonitoringEnabled`](https://developer.apple.com/documentation/uikit/uidevice/1620045-batterymonitoringenabled?language=objc) – mfaani Aug 11 '17 at 14:33
  • Everytime i open my app, i set ```batteryMonitoringEnabled```to ```YES```, if ```NO```, ```batteryStatus``` is ```unknown```, and the value is ```-1```, so i make sure i set it. Has this ivar influenced by any other factor? – Wakeen Aug 14 '17 at 02:08

1 Answers1

0

To monitor the changing battery level You can use the battery state notification UIDeviceBatteryStateDidChangeNotification and UIDeviceBatteryLevelDidChangeNotification

You can register your VC to receive the notification on change as follows -

 NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryStateDidChange:", name: UIDeviceBatteryStateDidChangeNotification, object: nil)
 NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryLevelDidChange:", name: UIDeviceBatteryLevelDidChangeNotification, object: nil)   

And then implement the selector methods

func batteryStateDidChange(notification: NSNotification){     
    // The stage did change: plugged, unplugged, full charge...
}

func batteryLevelDidChange(notification: NSNotification){     
   // The battery's level did change (98%, 99%, ...)
}
Kapil G
  • 4,081
  • 2
  • 20
  • 32
  • I test it, and it can't solve this problem, i get batteryLevel between two App, one is correct, another has this question which i descripe.I wanna know has any factor would influence it ? i check the methodList and ivarList, it is same as each App, i also check address, it same, i have no idea about it, thanks! – Wakeen Aug 11 '17 at 06:38