how to access device battery level from lock screen

670 Views Asked by At

I have been trying to replicate this feature found in the following app: Charge Alarm

My question is how are they able to access device's battery level when the screen is locked and the app is in the background state?

They send notification when the app is in background state. And they send this notification when device reaches a certain battery level.

NOTE: They are not able to do this if the app is put in background state by pressing home button. But if user locks the screen while the app is active this feature works really good.

2

There are 2 best solutions below

0
mobs_boss On BEST ANSWER

I went through this this tutorial

and this seems to be working perfectly. I made only one change, that is, in info.plist file I added a new property Application does not run in background & gave it a value YES.

1
Yash Bedi On

I'm not Sure You can get that information on lock screen:

Allow me to Tell you the whole process How to achieve the exact same functionality which is there in Charge Alarm App It is really Simple : Follow This :

Step 1 :
You Need to set the Background Fetch ON in Capabilities of your project,

Step 2 :

Turn On Battery Monitoring : UIDevice.current.isBatteryMonitoringEnabled = true in your AppDelegate.

Step 3 :

Get the Battery Level :

var batteryLevel : Float {
    get {
          return UIDevice.current.batteryLevel 
        } 
    }
}

Step 4 : Add the Observer in viewDidLoad() of your BaseViewController or any otherViewController :

    override func viewDidLoad(_ animated: Bool) {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange(_:)), name: NSNotification.Name.UIDeviceBatteryLevelDidChange, object: nil)
      }
     func batteryLevelDidChange(_ notify:Notification){
          // write code to post a local notification on lock screen with text like :  " YOUR DEVICE IS NOW AT xx% "
      }

Now to Set Up Back Ground Modes : Refer this

Step 5 :

For Local Notification Setup : Refer This

That's It, You have created the Same functionality, If you have any problem comment and I'll reply to earliest.