iOS开发Swift获取设备电池级别始终返回-1.0求助
Hey there! Let's work through why you're getting -1.0 when trying to fetch the battery level. I've reviewed your code, and here are the key fixes and checks you need to make:
1. You're probably testing on the iOS Simulator
The iOS Simulator doesn't have actual battery hardware, so it will always return -1.0 for batteryLevel no matter how you configure battery monitoring. This is the most common culprit here!
To get real battery data, you need to run your app on a physical iOS device (iPhone/iPad).
2. Add a notification listener for battery state changes
While you've correctly enabled battery monitoring in viewDidLoad, the system might take a moment to fetch the initial battery data. Adding a notification listener ensures you get updates whenever the battery state (charging/discharging) changes, so you'll always have the latest level available.
Here's your updated code with this fix:
import UIKit class FirstController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Enable battery monitoring UIDevice.current.isBatteryMonitoringEnabled = true // Listen for battery state changes to get updated level data NotificationCenter.default.addObserver( self, selector: #selector(batteryStateChanged), name: UIDevice.batteryStateDidChangeNotification, object: nil ) } deinit { // Clean up the notification observer to avoid memory leaks NotificationCenter.default.removeObserver(self) } var batteryLevel: Float { let rawLevel = UIDevice.current.batteryLevel // Return 0.0 instead of -1.0 if level is unavailable (for better UX) return rawLevel >= 0 ? rawLevel : 0.0 } @objc private func batteryStateChanged() { // This will print the updated level whenever the battery state changes print("Updated Battery Level: \(batteryLevel)") } @IBAction func onButtonClick(_ sender: Any) { print("Battery monitoring enabled: \(UIDevice.current.isBatteryMonitoringEnabled)") print("Current Battery Level: \(batteryLevel)") } }
Additional Notes
- The
-1.0value frombatteryLevelis Apple's official indicator that battery monitoring is disabled or the device can't provide battery data. Since you've enabled monitoring, this is almost certainly a simulator issue. - On a physical device, you should see values between
0.0(empty) and1.0(full) when you tap the button or when the battery state changes.
内容的提问来源于stack exchange,提问作者Sanjay Kumar

