0

I'm trying to include a battery feature to my widget, but I can't seem to get the mobile's battery percentage...

I tried:

import UIKit

struct BatteryControl {
    static func getBatteryPercent() -> Int {
        UIDevice.current.isBatteryMonitoringEnabled = true
        print("BATTERY : \(UIDevice.current.batteryLevel)")
        return Int(UIDevice.current.batteryLevel * 100)
    }
}

It just keeps showing that the battery is -1.0

EDIT SOLUTION: Simulator always showing the batter as -1.0, but whem testing it on a real deivce, it showed the correct value.

Sarvesh Sridhar
  • 387
  • 3
  • 3

1 Answers1

1

The battery monitoring must be enabled in the method didFinishLaunchingWithOptions of the AppDelegate

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UIDevice.current.isBatteryMonitoringEnabled = true
        return true
    }
Mickael Belhassen
  • 2,970
  • 1
  • 25
  • 46