如何获得Swift 5中的系统电池百分比?

如何获得Swift 5中的系统电池百分比?,swift,xcode,widgetkit,Swift,Xcode,Widgetkit,我试图在我的小部件中加入电池功能,但我似乎无法获得手机的电池百分比 我试过: import UIKit struct BatteryControl { static func getBatteryPercent() -> Int { UIDevice.current.isBatteryMonitoringEnabled = true print("BATTERY : \(UIDevice.current.batteryLevel)&quo

我试图在我的小部件中加入电池功能,但我似乎无法获得手机的电池百分比

我试过:

import UIKit

struct BatteryControl {
    static func getBatteryPercent() -> Int {
        UIDevice.current.isBatteryMonitoringEnabled = true
        print("BATTERY : \(UIDevice.current.batteryLevel)")
        return Int(UIDevice.current.batteryLevel * 100)
    }
}
它只是不断显示电池是-1.0

编辑
解决方案:模拟器始终将电池显示为-1.0,但当在实际设备上测试时,它显示了正确的值。

必须使用
AppDelegate
的方法
didFinishLaunchingWithOptions
启用电池监控

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UIDevice.current.isBatteryMonitoringEnabled = true
        return true
    }

你在真实设备上测试吗?我猜在模拟器上它总是会返回这个数字。不,在真实设备上测试它是可行的。模拟器总是返回-1.0