iPhone实时电量检测

如果你需要实时监控 iPhone 电池状态,这个代码资源挺适合的。通过 iOS 的UIDevice类,你可以简单地获取到电池电量和充电状态。这不只是基本的电池显示功能,还可以实时响应电池状态变化,适合健康追踪、游戏等需要即时反馈的应用。

实现的方法其实也简单,UIDevicebatteryLevelbatteryState属性,你只需要通过 KVONotificationCenter监听这些变化。代码也比较简洁,下面是个基本的 KVO 监听示例:

override func viewDidLoad() {
    super.viewDidLoad()
    UIDevice.current.isBatteryMonitoringEnabled = true
    UIDevice.current.addObserver(self, forKeyPath: "batteryLevel", options: .new, context: nil)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "batteryLevel" { let batteryLevel = UIDevice.current.batteryLevel print("电池电量: (batteryLevel * 100)%") } }

,别忘了在Info.plist中添加权限,尤其是在 iOS 13 及以后,用户隐私得注意。,这个资源对于 iOS 电池状态监控相当实用,快去试试吧!

zip 文件大小:63.71KB