Purple Wolf
Purple Wolf

Reputation: 397

How to get the systems Battery Percentage in Swift 5?

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.

Upvotes: 0

Views: 1108

Answers (1)

Mickael Belhassen
Mickael Belhassen

Reputation: 3342

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
    }

Upvotes: 1

Related Questions