You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift获取设备充电状态异常:变量未随充电状态更新

解决Swift中电池状态监听不更新变量的问题

嘿,我帮你排查了下代码,发现几个关键问题导致chargingStatus始终没变化,咱们一步步来修复:

  • 未正确引用设备电池状态
    你在batteryStateDidChange方法里直接用了batteryState,但这个变量并没有明确指向当前设备的电池状态!应该替换成UIDevice.current.batteryState,不然编译器根本不知道你要访问的是哪个对象的电池状态,导致分支逻辑完全没执行。

  • 确认初始化函数是否被调用
    你的declaration()函数负责开启电池监控和添加通知监听,但如果这个函数没被执行(比如没在viewDidLoad、init等合适的地方调用),那整个监听机制根本没启动,自然不会收到电池状态变化的通知。

  • 可选类型没必要的使用
    chargingStatus被定义成Bool? = false,其实这里完全不需要可选型,直接用var chargingStatus: Bool = false更稳妥,避免后续使用时碰到意外的nil情况。

下面是修正后的完整代码示例:

var chargingStatus: Bool = false

func setupBatteryMonitoring() {
    UIDevice.current.isBatteryMonitoringEnabled = true
    NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: UIDevice.batteryStateDidChangeNotification, object: nil)
}

@objc func batteryStateDidChange(_ notification: Notification) {
    let currentBatteryState = UIDevice.current.batteryState
    print("BATTERY STATE \(currentBatteryState)")
    
    switch currentBatteryState {
    case .unplugged, .unknown:
        chargingStatus = false
    case .charging:
        chargingStatus = true
    case .full:
        chargingStatus = false
        print("charging or full")
    }
}

最后还有个小提醒:iOS模拟器的电池状态模拟有时候不太靠谱,建议用真实设备测试;另外记得在合适的时机(比如视图控制器的viewDidLoad)调用setupBatteryMonitoring()哦。

内容的提问来源于stack exchange,提问作者King

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:21:57